【发布时间】:2018-02-14 14:40:05
【问题描述】:
我已经尝试从 jQuery.post 转移到一个名为 fetch 的默认功能来发出请求。我已经意识到,看起来相同的查询具有不同的行为。
jQuery.post:
jQuery.post({
type: "POST",
url: '/core/comment/add',
data: {
type: "article",
identity: 1931,
body: "Some stuff"
}
}).done(function() {
console.log(arguments);
}).fail(function() {
console.log("fail");
});
获取:
fetch('/core/comment/add', {
method: 'POST',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type':'application/json',
},
body: JSON.stringify({
type: "article",
identity: 1931,
body: "Some stuff"
})
}).then(function(response) {
console.log(response);
}).catch(function(e) {
console.log(e);
});
在jQuery.post 情况下,一切正常,但fetch 返回我的状态为404。我还尝试添加credentials: 'same-origin' 选项,尝试发送不带JSON.stringify 和标题的数据,但没有已更改 - $_POST 为空。
那么有什么区别以及如何实现相同的行为?
【问题讨论】:
-
如果您进入浏览器 devtools 的“网络”窗格并重新加载并检查这两个请求,您会看到什么不同? Content-Type 值是否相同?响应体是否相同?那里显示的 jQuery 请求的响应正文实际上是 JSON 吗?
-
什么是
i.core.request.fetchLocal(…)?与直接调用本机fetch(…)方法有什么不同?您是否尝试过仅使用本机fetch(…)方法而不是i.core.request.fetchLocal(…)的相同请求? -
i.core.fetchLocal 只需检查
/符号是 url 的第一个并返回相同的提取。我想,我会编辑这篇文章以免人们误解。 -
@sideshowbarker 网络工具显示了差异 (pastebin.com/yw9xj5ZD)。 jQuery.post 将数据作为表单数据发送并作为请求负载提取。响应内容类型不同,因为 404 发送一个 html 页面。
-
pastebin.com/yw9xj5ZD 表示 jQuery 正在以 'tapplication/x-www-form-urlencoded' 的形式发送数据;请参阅下面的答案,了解如何使用 Fetch API 做到这一点。至于为什么“应用程序/json”获取请求没有按预期工作,我猜这是因为后端不希望收到“应用程序/json”但期望“应用程序/x-www-form-urlencoded”数据代替?
标签: javascript jquery fetch-api