为什么 $.post() 工作但不获取工作
why does $.post() work but not fetch work
我只是想将我的 ajax 代码转换为 fetch,但 fetch 似乎不起作用。
- 这是为什么?
- 我该如何解决?
- 如果需要,我可以提供更多信息。
这是我的js代码:
fetch("login.php", {
method: "POST",
body: JSON.stringify(data),
headers: {
"Content-Type": "application/json"
},
}).then(response =>
{
response.clone().text().then(resp =>
{
console.log(resp);
if(resp.trim()=="ok")
{
window.location = "tab.html";
}
})
});
//ajax code underneath that's the same but works
$.post("login.php", {username: $("#user").val(), password: $("#password").val()}).done(function(response)
{
console.log(response);
if(response.trim()=="ok")
{
window.location = "tab.html";
}
});
以为我可以回答这个问题。花了一段时间才弄明白,但最终还是到了那里。只需像这样使用表单数据方法:
let data = new FormData;
data.append("user", $("#user").val());
data.append("password", $("#password").val());
fetch("login.php", {
method: "POST",
body: data,
}).then(response =>
{
response.text().then(text =>
{
console.log(text);
if(text.trim() == "ok")
{
window.location = "tab.html";
}
})
});`
我只是想将我的 ajax 代码转换为 fetch,但 fetch 似乎不起作用。
- 这是为什么?
- 我该如何解决?
- 如果需要,我可以提供更多信息。
这是我的js代码:
fetch("login.php", {
method: "POST",
body: JSON.stringify(data),
headers: {
"Content-Type": "application/json"
},
}).then(response =>
{
response.clone().text().then(resp =>
{
console.log(resp);
if(resp.trim()=="ok")
{
window.location = "tab.html";
}
})
});
//ajax code underneath that's the same but works
$.post("login.php", {username: $("#user").val(), password: $("#password").val()}).done(function(response)
{
console.log(response);
if(response.trim()=="ok")
{
window.location = "tab.html";
}
});
以为我可以回答这个问题。花了一段时间才弄明白,但最终还是到了那里。只需像这样使用表单数据方法:
let data = new FormData;
data.append("user", $("#user").val());
data.append("password", $("#password").val());
fetch("login.php", {
method: "POST",
body: data,
}).then(response =>
{
response.text().then(text =>
{
console.log(text);
if(text.trim() == "ok")
{
window.location = "tab.html";
}
})
});`