开发者

Make several .ajax calls on the same page fire in order

I have several jQuery .ajax calls on the same page like:

$.ajax({
    url: "page1.php",
    cache: false,
    success: function(html) {
        //do some stuff with returned html
    }
});

When I run the page some may complete out of order. I'm guessi开发者_如何学运维ng they are all starting at the same time.

Is there a way for me to queue them up so they fire in a particular order and not until the previous one completes?


You can chain them, like this:

$.ajax({
    url: "page1.php",
    cache: false,
    success: function(html) {
        //do some stuff with returned html
    },
    complete: function(xhr) {
        // do your next call
    }
});

Wait for the first to complete, and then make your next one. A better approach though is to do it like this:

var waiting = 0;

// for each request:
waiting++;
$.ajax({
    url: "page1.php",
    cache: false,
    success: function(html) {
        // save the returned stuff in an array
    },
    complete: function(xhr) {
        if (--waiting <=0) { // == would probably suffice, but i like to be safe.
          //process the result
        }
    }
});

This reduces the load time, and allows you to process it in order.


Yes you can do this in the way you write your code. By making the next AJAX call in the callback function of the first you could chain requests:

$.ajax({
    url: "page1.php",
    cache: false,
    success: function(html) {
        // Make another call here
        $.ajax({
            url: "page1.php",
            cache: false,
            success: function(html) {
                // and so on
            }
        });
    }
});


You may take a look at the following plugin which allows you to queue requests.


AjaxQueue plugin to the rescue!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜