开发者

How to confirm when more than one AJAX call has completed?

开发者 https://www.devze.com 2023-03-04 23:10 出处:网络
$(document).ready(function() { $(\"#list1\").jqGrid({ url: \'example1.php\', /*balabala...*/ gridComplete: function() {
$(document).ready(function() {
    $("#list1").jqGrid({
        url: 'example1.php',
        /*balabala...*/
        gridComplete: function() {

        }
    });

    $("#list2").jqGrid({
        url: 'example2.php',
      开发者_C百科  /*balabala...*/
        gridComplete: function() {

        }
    });

    /*I want to do something here, but the above grids must be both complete first.*/
    Something...
});

How should I do ? Thanks!


The easiest way is to put your "something" in the gridComplete callbacks but have the two callbacks check that the other one has finished. Something along these lines:

function do_something_wonderful() {
    // This is the awesome stuff that you want to
    // execute when both lists have loaded and finished.
    // ...
}

var one_done = false;
function done_checker() {
    if(one_done) {
        // The other one is done so we can get on with it.
        do_something_wonderful();
    }
    one_done = true;
}

$("#list1").jqGrid({
    //blah blah blah
    gridComplete: done_checker
});
$("#list2").jqGrid({
    //blah blah blah
    gridComplete: done_checker
});

This nicely extends to more than two lists with a couple small modifications:

  • use var how_many_done = 0; instead of one_done.
  • Do a ++how_many_done; instead of one_done = true; and move it to the top of done_checker.
  • Replace the if(one_done) with if(how_many_done == number_of_tasks) where number_of_tasks is how many AJAX tasks you have.

The general version would look sort of like this:

var number_of_tasks = 11; // Or how many you really have.
var how_many_done   = 0;
function done_checker() {
    ++how_many_done;
    if(how_many_done == number_of_tasks) {
        // All the AJAX tasks have finished so we can get on with it.
        do_something_wonderful();
    }
}

An even better version would wrap up the state in a closure:

var done_checker = (function(number_of_tasks, run_when_all_done) {
    var how_many_done = 0;
    return function() {
        ++how_many_done;
        if(how_many_done == number_of_tasks) {
            // All the AJAX tasks have finished so we can get on with it.
            run_when_all_done();
        }
    }
})(do_something_wonderful, 11);


You should be currently using the jquery deferred objects.

0

精彩评论

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