开发者

Jquery AJAX one by one

I am trying to run two ajax requests one after the other. So, I could use the ajax success() function:

$.ajax({
    ...
    success: function() {
        //here the second ajax request
    }
});

The problem is, that the first ajax request gets only executed, when an condition is true. So my code looks like:

if($cond) {
    $.ajax({
        ...
    });
}
$.ajax({
    ...
});

How can I run these request ony by one? Or is it standard that the second gets only exe开发者_JS百科cuted when the first has finished?


jQuery 1.5 introduced deferred objects [docs], and $.ajax [docs] is returning one:

$.ajax({
   //...
}).then(function() {
    $.ajax({
        //...
    });
});

Reference: deferred.then [docs]

Update:

In your case you can do this:

var deferred = jQuery.Deferred();
deferred.resolve();  // <- I think you need this here but I'm not sure.

if($cond) {
    deferred = $.ajax({
        ...
    });
}
deferred.then(function() {
    $.ajax({
      //...
    });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜