ajax - Wordpress 在使用 fetch API 的 ajax 调用上返回 400 Bad Request
问题描述
我正在使用 fetch API 语法对 admin-ajax.php 进行 Ajax 调用。下面是调用后端脚本的代码:
fetch(ajax_obj.ajaxurl, {
method: "POST",
mode: "cors",
cache: "no-cache",
credentials: "same-origin",
body: JSON.stringify(this.data),
headers: {
"Content-Type": "application/json"
}
})
并得到 400 Bad Request 响应。
有人能告诉我这个要求哪里不对吗?
在chrome中检查网络开发工具时,我可以看到发送的正文是好的,url也是好的……据我所知,4xx状态码是客户端的错误,所以我甚至不看服务器端代码...如果我错了,请给我反馈...
实际上,我有这样的 jQuery ajax 调用:
this.data = {
'action': 'ajax_product_query',
'locations': this.locations,
'type': this.category != '' ? this.category : [],
'all-locations': this.filters['locationFilter'].all.checked,
'page': ajax_obj.current_page
};
$.ajax({
url: ajax_obj.ajaxurl,
method: 'post',
dataType: 'json',
data: this.data,
beforeSend: function(xhr) {
button.innerHTML = 'Loading...';
},
success: (data) => { ...
......它就像一个魅力......
比,愿意删除 jQuery 依赖,想要将 jQuery ajax 调用转换为 Fetch API 语法,如下所示:
fetch(ajax_obj.ajaxurl, {
method: "POST",
mode: "cors",
cache: "no-cache",
credentials: "same-origin",
body: JSON.stringify(this.data),
headers: {
"Content-Type": "application/json"
}
})
.then(response => response.json()) ...
然后请求变成了 400 个错误请求......
谢谢!
解决方案
因为在 JS 获取 'POST' 请求后,您无法在 PHP 中获取 $_POST 数据。肮脏的解决方案。您可以在“/wp-admin/admin-ajax.php”中添加此代码来解决此问题:
if ( !empty( trim( file_get_contents("php://input" ) ) ) ) {
$post = trim(file_get_contents("php://input"));
$_POST = ( array ) json_decode( $post );
$_REQUEST['action'] = $_POST['action'];
}
或者尝试找到更好的解决方案。
PS对不起我的英语
推荐阅读
- javascript - 如何在嵌入式音频上应用 JavaScript 函数?
- php - 当用户输入错误的url php时如何重定向到404错误页面
- c# - 如何使用 Peta Poco 将自动递增的 id 设置为另一列
- sql-server - Import-Module SQLServer 无法加载文件或程序集 Microsoft.SqlServer.ConnectionInfo 或 Microsoft.SqlServer.Smo
- docker - Golang 和 Gitlab 持续集成
- django - 如何翻译 Django 过滤器中的字段?
- google-apps-script - 如何动态地将值放入列中?
- spring-boot - 多租户 Spring Boot 应用程序中的 Hibernate Search 初始化索引
- python - pywinauto 打印控件标识符不显示所需的控件按钮
- python - 在python 3中按下X windows按钮时如何返回上一个窗口