jQuery Ajax:等到第一个调用结束,发送另一个请求$ .Deferrent

时间:2012-10-18 09:30:50

标签: jquery jquery-deferred

我正面临Deferrent的问题以及如何在这种特定情况下使用它。

情景如下。

我有一个循环,我将一些数据发送到服务器。例如:

var array = [{"effect":"save","params":["login_0_form_form_login"],"url":"http://www.example.local/login"},{"effect":"redirect","params":["index"],"url":"http://www.example.local/index"}];

$.each(array,function(key,payload) {

 $.post(payload.url,payload);

});

然后是一个处理ajax调用结果的成功方法。

App.success = function(result){
   //Here I am deciding what to do with the result and checking for errors or warnings

   if(result.notification.success) {
      //Everything is good
   }
   else if(result.notification.error) {
      //Something is wrong, somehow stop the other ajax call  
   }
}

尽管如此,我面临的问题是,服务器可以返回错误,例如,错误的登录数据。在这种情况下,尽管从服务器返回错误的登录数据,它将重定向。我需要以某种方式控制先前的请求是否返回错误。如果是,请不要发布。

我试图在$ .when函数中返回$ .post并使用$ .then。但我没有实现我所希望的目标。

1 个答案:

答案 0 :(得分:2)

你不应该使用循环 - AJAX调用将立即(并行)启动,而不是一次运行一个。

我会使用递归回调循环依次处理每个动作,并结合单独的$.Deferred对象,以便您收到通知:

function processActions(actions) {
    var def = $.Deferred();

    (function nextAction() {
        var action = actions.shift();  // dequeue the next action
        if (action) {
            $.ajax(...).done(nextAction).fail(function() {
                def.reject();  // there was an error
            });
        } else {
            def.resolve();     // all done
        }
    })();  // invoke this function immediately

    return def.promise();
}
相关问题