wordpress 中的一个简单的 Ajax 调用没有给出预期的输出 [英] A simple Ajax call in wordpress doesn't give the expecetd output
问题描述
这是我的 javascript 文件:-
Here is my javascript file:-
jQuery(document).ready( function($) {
$('#test_button').click(function(e){
alert("test");
$.ajax({
url : my_ajax_object.ajaxurl ,
type : 'post',
dataType : 'json',
data : {
action : 'do_ga'
},
complete: function(res, status) {
if( status == 'success' ) {
console.log("success "+res);
} else {
console.log("fail "+res);
}
}
});
});
});
这是我在functions.php中的php代码:-
here is my php code in functions.php:-
function do_ga() {
die("test" );
}
add_action( 'wp_ajax_do_ga', 'do_ga' );
add_action( 'wp_ajax_nopriv_do_ga', 'do_ga' );
//this is the script en queuing
function my_enqueue() {
wp_enqueue_script( 'ga-loadmore', get_template_directory_uri() . '/pl-custom/front-end-assets/js/ga-loadmore.js', array('jquery') );
wp_localize_script( 'ga-loadmore', 'my_ajax_object',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
所以,当点击id为#test_button"的按钮时,它输出的不是success [object][object],而是fail [object][object].这里需要做什么.确切地说,我想要成功测试".请在解决方案中需要的任何地方添加 json_encode 和解码.谢谢
So,upon the click of the button with id "#test_button" , instead of outputting success [object][object] , it outputs fail [object][object]. What needs to be done here. Precisely , i want "success test". please add the json_encode and decode wherever required in the solution.Thanks
推荐答案
我已经将 PHP 代码分离到另一个文件中并包含在 functions.php 中,并且还分离了排队,并稍微更改了请求的语法.我在此附上我的代码并且它有效:
I've separated the PHP code in another file and included it in functions.php and also separated the enqueuing, and changed the syntax of the request a little. I hereby attach my code and it works:
function do_ga() {//server code
$x="test";
wp_die( $x);
exit;
}
add_action( 'wp_ajax_do_ga', 'do_ga' );
add_action( 'wp_ajax_nopriv_do_ga', 'do_ga' );
客户端(已经入队):-
client side(already enqueued):-
jQuery(document).ready( function($) {
$('#test_button').click(function(e){
url = window.location.origin + '/wp-admin/admin-ajax.php?action=do_ga';
alert("test");
$.ajax({
async: true,
type: 'POST',
url: url,
data: {
'my_number':1 //you need not pass data
},
complete: function(res, status) {
if( status == 'success' ) {
alert("success "+ res.responseText);
} else {
alert("unable to process request");
}
}
})
});
});
这篇关于wordpress 中的一个简单的 Ajax 调用没有给出预期的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!