【发布时间】:2019-06-07 19:25:54
【问题描述】:
我正在使用 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中查看网络开发工具时,可以看到发送的body是ok的,url也是ok的... ...据我所知,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 个错误请求......
谢谢!
【问题讨论】:
-
我们需要查看更多代码来提供帮助。
-
究竟是什么代码...我会共享后端脚本,但正如我提到的,该过程从前端失败...
-
好吧,那就适合你自己吧。祝你好运!
-
好的,我会尝试给出更多解释...谢谢
-
你找到解决这个问题的方法了吗?