为什么$ .post()可以工作但不能提取

时间:2018-08-14 09:31:37

标签: ajax login fetch

我只是想将我的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";
    }
});

1 个答案:

答案 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";
        }
    })
});`