为什么async ajax请求不起作用?

时间:2016-07-13 11:25:25

标签: javascript jquery html ajax asynchronous

我是javascript的新手。我使用此脚本在我的api中进行身份验证:

function try_login() {
    $.ajax({
        type: "POST",
        url: "http://some.api/auth",
        dataType: 'json',
        async: false,
        data: {
            username: document.getElementById('username').value,
            password: document.getElementById('password').value
        },
        success:  function (data)
        {
            // alert(data.jwt_token);
            window.sessionStorage.setItem('token', data.jwt_token);
            // alert(window.location);
            window.location.replace("/index.html");
            //  alert(window.location);
            return false;
        }
       // success: successLogin,
    });
}

这是我的HTML(也是我使用bootstrap):

<form class="form-signin" role="form">
    <h2 class="form-signin-heading">Please sign in</h2>
    <input id="username" type="username" class="form-control" placeholder="Username" required="" autofocus="">
    <input id="password" type="password" class="form-control" placeholder="Password" required="">
    <button class="btn btn-lg btn-primary btn-block" type="submit" id="login_btn" onclick="try_login()">Sign in</button>
  </form>

我有两个麻烦。 首先,如果我在true上更改async或删除它(因为在ajax中默认为async true),为什么它不会向api发送post请求,它只会刷新页面。

其次,当我使用async false post请求时,它会向api发出正常请求并接收正常响应。在sessionStorage中保存令牌可以很好地工作,但window.location.replace不会在下一页上重定向。我也尝试了很多种,例如:

window.location = "/index.html"

window.location.href = "/index.html"

并尝试设置非相对路径&#34; www.mysite.com/index.html"。

Chrome警告说同步请求已弃用,但我第一次遇到麻烦,因为您可以看到我不知道如何使用异步请求。 此外,它似乎是一个魔术,但如果我在成功函数中取消注释我的所有字段,firefox会将我重定向到&#34; index.html&#34;。

拜托,帮助我!

1 个答案:

答案 0 :(得分:1)

  

首先,为什么我会在true上更改async或删除它(因为在ajax中默认为async true),它不会向api发送post请求,它只会刷新页面。

因为您提交的表单涉及拆除页面并取消任何正在进行的ajax请求。

  

其次,当我使用async false post请求时,它会向api发出正常请求并接收正常响应。在sessionStorage中保存令牌可以很好地工作,但是window.location.replace不会在下一页重定向。

因为您要提交表单。 return false回调中的success对表单的submit事件没有任何影响。如果要阻止从success处理程序中提交表单,请使用jQuery(而不是try_login属性)挂钩onclick,接受事件对象,然后使用preventDefault()在它上面。

在我看来,你真的不想提交表单,只是想用它来触发ajax。如果是这样的话,就没有必要让你的ajax同步(并且有很好的理由):

function try_login() {
    $.ajax({
        type: "POST",
        url: "http://some.api/auth",
        dataType: 'json',
        data: {
            username: document.getElementById('username').value,
            password: document.getElementById('password').value
        },
        success: function(data) {
            window.sessionStorage.setItem('token', data.jwt_token);
            window.location.replace("/index.html");
        }
    });
    return false;
}

删除onclick并将其连接起来:

$("any-css-selector-for-the-form").on("submit", try_login);

您可能希望显示某些内容以表明请求正在进行中。