如何在 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屋!