我只是想将我的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";
}
});
答案 0 :(得分:1)
我可能会回答这一问题。花了一段时间才弄清楚,但最终到了那里。只需使用如下形式的表单数据方法即可:
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";
}
})
});`