尽管有许多类似的帖子,但所有提议的解决方案都不适合我,所以我们来了。
我有以下脚本:
jQuery(\'#term\').keyup(ajaxChange);
function ajaxChange(){
var newFormChange = jQuery("#term").val();
alert (newFormChange);
jQuery.ajax({
type:"POST",
action: "my_test_action",
url: "/wp-admin/admin-ajax.php",
data: newFormChange,
success:function(data){
console.log(data);
}
});
return false;
}
PHP如下所示:function my_test_action() {
$var = "this is a test";
wp_send_json($var);
die();
}
add_action( \'wp_ajax_my_test_action\', \'my_test_action\' );
add_action( \'wp_ajax_nopriv_my_test_action\', \'my_test_action\' );
我也尝试过:echo json_encode($var)
或echo $var
, 而不是wp_send_json()
但该函数在浏览器控制台中始终返回0!我的其他AJAX调用可以工作,例如,我有另一个调用PHP脚本的调用,该脚本调用WP查询并显示一些帖子,它工作得很好。
EDIT : 以下是如何包含我的脚本:
function add_js() {
if (is_page_template()) {
wp_enqueue_script( \'mycustomscript\', get_stylesheet_directory_uri().\'/js/mycustomscript.js\', array(\'jquery\'), \'1.0\', true );
wp_localize_script(\'mycustomscript\', \'ajaxurl\', admin_url( \'admin-ajax.php\' ) );
}
}
add_action(\'wp_enqueue_scripts\', \'add_js\');
我认为问题来自newFormChange
变量,因为jQuery(this).serialize();
一开始不起作用,因为表单未提交,但只有一个字段发生了更改。所以我用var代替了它newFormChange = jQuery("#term").val();
但也许有个问题url: "/wp-admin/admin-ajax.php"
我哪里弄错了?谢谢