我试图在wordpress世界中实现ajax,但现在被卡住了。假设在未触发ajax时调用函数挂钩。
我检查网络
管理ajax。php被调用,但响应为null意味着未调用getsomething函数有人知道吗?
下面是我的代码。
功能。php
function my_resource() {
wp_enqueue_script(\'my-jquery\',get_template_directory_uri().\'/jqfunctions.js\');
wp_localize_script( \'my-jquery\', \'myback\',
array(\'ajax_url\' => admin_url( \'admin-ajax.php\' )));
}
add_action(\'wp_enqueue_scripts\', \'my_resource\');
JQ功能。js公司
jQuery(document).ready(function(){
jQuery("#popular").click(function(){
console.log(\'popular clicked\');
jQuery.ajax({
url: myback.ajax_url,
type: \'POST\',
dataType: \'json\',
data:{
action: \'getsomething\'
},
success: function( response ){
console.log("This is response...");
console.log(response);
},
error: function( error ){
console.log(\'AJAX error callback....\');
console.log(error);
}
});
});
});
管理ajax。php
function getsomething(){
wp_send_json_error(\'hey\');
}
add_action(\'wp_ajax_nopriv_getsomething\', \'getsomething\');
add_action(\'wp_ajax_getsomething\', \'getsomething\');
最合适的回答,由SO网友:cybmeta 整理而成
我已经测试了你的代码,它运行得很好。我刚刚声明了JavaScript的依赖项,因此它在jQuery之后被正确加载。我就是这样测试的:
functions.php
function my_resource() {
wp_enqueue_script(\'my-jquery\',get_template_directory_uri().\'/jqfunctions.js\', array(\'jquery\'));
wp_localize_script( \'my-jquery\', \'myback\',
array(\'ajax_url\' => admin_url( \'admin-ajax.php\' )));
}
add_action(\'wp_enqueue_scripts\', \'my_resource\');
function getsomething(){
wp_send_json_error(\'hey\');
}
add_action(\'wp_ajax_nopriv_getsomething\', \'getsomething\');
add_action(\'wp_ajax_getsomething\', \'getsomething\');
jqfunctions.js
jQuery(document).ready(function(){
jQuery("#popular").click(function(e){
e.preventDefault();
console.log(\'popular clicked\');
jQuery.ajax({
url: myback.ajax_url,
type: \'POST\',
dataType: \'json\',
data:{
action: \'getsomething\'
},
success: function( response ){
console.log("This is response...");
console.log(response);
},
error: function( error ){
console.log(\'AJAX error callback....\');
console.log(error);
}
});
});
});