如何在wordpress中调用ajax [英] How to call ajax in wordpress
问题描述
我的Ajax调用输出始终显示0,因为输出不知道为什么
My ajax call output is always showing 0 as output don't know why
在functions.php
中我有此代码
function get_data() {
$abc = '1';
$result = $wpdb->get_results("SELECT * FROM ".$wpdb->options ." WHERE option_name LIKE '_transient_%'");
echo $result; //returning this value but still shows 0
wp_die();
}
add_action( 'wp_ajax_nopriv_get_data', 'get_data' );
add_action( 'wp_ajax_get_data', 'get_data' );
我的ajax调用在javascript中
And my ajax call is in a javascript
$('body').on("click", ".re-reset-btn", function(e){
var panel = $('#re-compare-bar');
$.ajax({
type : "GET",
dataType : "json",
url : "/wp-admin/admin-ajax.php",
data : {action: "get_data"},
success: function(response) {
alert("Your vote could not be added");
alert(response);
}
});
$("#re-compare-bar-tabs div").remove();
$('.re-compare-icon-toggle .re-compare-notice').text(0);
});
我在不使用插件的情况下在wordpress中进行ajax调用,但没有得到我要传递的内容.即使输出$ abc仍然显示0.
I'm making ajax call in wordpress without use of plugin but not getting what I'm passing.Even If I output $abc still it shows 0.
推荐答案
在后端,WordPress本身定义了全局ajaxurl变量.
In backend there is global ajaxurl variable defined by WordPress itself.
此变量不是由WP在前端创建的.这意味着,如果要在前端使用AJAX调用,则必须自己定义此类变量.
This variable is not created by WP in frontend. It means that if you want to use AJAX calls in frontend, then you have to define such variable by yourself.
执行此操作的好方法是使用wp_localize_script.
Good way to do this is to use wp_localize_script.
假设您的AJAX调用位于my-ajax-script.js文件中,然后为该JS文件添加wp_localize_script,如下所示:
Let's assume your AJAX calls are in my-ajax-script.js file, then add wp_localize_script for this JS file like so:
function my_enqueue() {
wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/my-ajax-script.js', array('jquery') );
wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
本地化JS文件后,可以在JS文件中使用my_ajax_object对象:
After localizing your JS file, you can use my_ajax_object object in your JS file:
jQuery.ajax({
type: "post",
dataType: "json",
url: my_ajax_object.ajax_url,
data: formData,
success: function(msg){
console.log(msg);
}
});
这篇关于如何在wordpress中调用ajax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!