Wordpress admin-ajax.php 400 错误请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48025825/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Wordpress admin-ajax.php 400 bad request
提问by ikalangita
I have a strange and frustrating behaviour of wordpress admin-ajax.php file, when i make an ajax request it returns 400 error bad request.
我对 wordpress admin-ajax.php 文件有一个奇怪且令人沮丧的行为,当我发出 ajax 请求时,它返回 400 错误错误请求。
(function( $ ) {
var ajaxscript = { ajax_url : 'mydomain.com/wp-admin/admin-ajax.php' }
$.ajax({
url : ajaxscript.ajax_url,
data : {
action : 'cart_clb',
id : 1
},
method : 'POST',
success : function( response ){ console.log(response) },
error : function(error){ console.log(error) }
})
})(jQuery)
And inside my functions.php
在我的functions.php里面
add_action( 'wp_ajax_post_cart_clb', 'cart_clb' );
add_action( 'wp_ajax_nopriv_post_cart_clb', 'cart_clb' );
function cart_clb(){
echo json_encode($_POST);
die();
}
As said above when i execute the request :
如上所述,当我执行请求时:
mydomain.com/wp-admin/admin-ajax.php 400 (Bad Request)
{readyState: 4, getResponseHeader: ?, getAllResponseHeaders: ?, setRequestHeader: ?, overrideMimeType: ?,?…}
Someone could help me to please? thank you.
有人可以帮我取悦吗?谢谢你。
回答by Ihor Vorotnov
First, use full and absolute url, with protocol (or at least protocol-independent form):
首先,使用完整和绝对 url,使用协议(或至少与协议无关的形式):
var ajaxscript = { ajax_url : '//mydomain.com/wp-admin/admin-ajax.php' }
Second, your ajax action name is not the php callback function name but the dynamic part of the hook wp_ajax_{action_name} / wp_ajax_nopriv_{action_name}, so in your case it should be:
其次,您的 ajax 操作名称不是 php 回调函数名称,而是 hook 的动态部分wp_ajax_{action_name} / wp_ajax_nopriv_{action_name},因此在您的情况下,它应该是:
data : {
action : 'post_cart_clb',
id : 1
},
回答by Lathiya Fenil
I have modified your code and look at this :
我已经修改了你的代码,看看这个:
(function( $ ) {
var ajaxscript = { ajax_url : 'mydomain.com/wp-admin/admin-ajax.php' }
$.ajax({
url : ajaxscript.ajax_url,
data : {
action : 'post_cart_clb',
id : 1
},
method : 'POST', //Post method
success : function( response ){ console.log(response) },
error : function(error){ console.log(error) }
})
})(jQuery)
This is the syntax of WordPress ajax : wp_ajax_{Your_action_name} wp_ajax_nopriv_{Your_action_name}
这是 WordPress ajax 的语法: wp_ajax_{Your_action_name} wp_ajax_nopriv_{Your_action_name}
回答by Claudio Ferraro
In Vanilla JavaScript You get a Bad Request if You don't append this header to the POST request:
在 Vanilla JavaScript 中,如果您不将此标头附加到 POST 请求,则会收到错误的请求:
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;');
So please be sure that jQuery appends as well that header.
所以请确保 jQuery 也附加了该标题。

