调用wordpress admin-ajax.php返回错误请求400



我知道很多人都在问这个问题。我遵循了所有的解决方案,但仍然得到了错误。我想要的是通过ajax调用PHP函数从管理页面上的表单提交。这是我的代码

function myFunction()
{
echo "DONE";
wp_die();
}
add_action('wp_ajax_my_function', 'myFunction); 
add_action('wp_ajax_nopriv_my_function', 'myFunction');//i know I don't need this line because I just want to call from admin page 
wp_register_script("my_fast_generate_script", my_dir_url . 'assets/js/ajax-my-fast-generate.js', array('jquery'));
wp_localize_script('my_fast_generate_script', 'my_fast_generate_Ajax', array('ajaxurl' => admin_url('admin-ajax.php'))); 
wp_enqueue_script('my_fast_generate_script');

ajax-my-fast-generate.js

jQuery(function ($) {
$(document).ready(function () {
// id dari button ketika diklik
$('#fast_generate').on('click', function (e) {
e.preventDefault();

console.log("success called until here");
$.ajax({
type: 'POST',
url: my_fast_generate_Ajax.ajaxurl, //diregister di index
dataType: 'json',
data: {
action: 'myFunction',
},
success: function (response) {
console.log("never executed here");
},
error: function (errorThrown) {
console.log(errorThrown);
},
});
});
})
});

作为附加信息,我使用nginx为我的web服务。我已经将整个WordPress文件夹的文件权限更改为777,并在我的WordPress根目录中添加了。htaccess,但错误仍然发生。

实际上我认为错误是在你的Javascript。Wordpress期望的"动作"是什么?参数是"wp_ajax_"或者"wp_ajax_nopriv_",所以在你的例子中应该是:

"wp_ajax_my_function在你的js中,你使用的是"myFunction"这实际上是函数名但wordpress不关心这个,它查看的是动作名,而不是动作使用的回调

所以最终的JS代码应该是:
jQuery(function ($) {
$(document).ready(function () {
// id dari button ketika diklik
$('#fast_generate').on('click', function (e) {
e.preventDefault();

console.log("success called until here");
$.ajax({
type: 'POST',
url: my_fast_generate_Ajax.ajaxurl, //diregister di index
dataType: 'json',
data: {
action: 'my_function', <---- edited this
},
success: function (response) {
console.log("never executed here");
},
error: function (errorThrown) {
console.log(errorThrown);
},
});
});
})
});

再试一次,让我们知道

您已经将dataType设置为json,这是服务器响应所期望的数据类型。但是您的函数只响应"DONE"而不是json数据,因此删除dataType。您也可以删除type.

$.ajax({
url: my_fast_generate_Ajax.ajaxurl,
data: {
action: 'my_function',
},
success: function(response) {
console.log("This is the response: "+response);
},
error: function(errorThrown) {
console.log(errorThrown);
},
});

最新更新