为什么$ .post()工作但不工作

问题描述 投票:1回答:1

我只是想将我的ajax代码转换为fetch但是fetch只是似乎不起作用。

  1. 这是为什么?
  2. 我该如何解决?
  3. 如果需要,我可以提供更多信息。

这是我的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";
    }
});
ajax login fetch
1个回答
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";
        }
    })
});`
© www.soinside.com 2019 - 2024. All rights reserved.