jQuery链ajax调用

时间:2014-11-25 00:59:33

标签: jquery promise

我不能为我的生活理解为什么这不起作用......

function Register(email, password) {

var data = {
    Email: email,
    Password: password,
    ConfirmPassword: password
};

return $.ajax({
    type: 'POST',
    url: baseUrl + 'api/Account/Register',
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify(data)
})

}

function Login(email, password) {

var data = {
    grant_type: 'password',
    username: email,
    password: password
};

return $.ajax({
    type: 'POST',
    url: baseUrl + 'Token',
    data: data
}).done(function (data) {
    sessionStorage.setItem(tokenKey, data.access_token);
});

}

现在......我想注册,然后点击一下按钮登录...

var email = $('input[name="email"]').val();
var password = $('input[name="password"]').val();

Register(email, password).then(Login(email, password))

但是,该代码不会按顺序调用它们。它通常首先登录。

我也尝试过done()和when(),但老实说,我不明白其中的差异并希望得到一些帮助...... 哭泣

2 个答案:

答案 0 :(得分:1)

我认为问题在于它正在立即评估Login(email, password)

尝试: Register(email, password).then(function() { Login(email, password); });

答案 1 :(得分:1)

function Register(email, password) {

    var data = {
        Email: email,
        Password: password,
        ConfirmPassword: password
    };

    return $.ajax({
        type: 'POST',
        url: baseUrl + 'api/Account/Register',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(data),
        success: function(msg) {
            Login(email, password);
        }
    })

}