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

后端 未结 2 1891
有刺的猬
有刺的猬 2021-01-16 02:47
$(document).ready(function() {
    $(\"#list1\").jqGrid({
        url: \'example1.php\',
        /*balabala...*/
        gridComplete: function() {

        }
    })         


        
相关标签:
2条回答
  • 2021-01-16 03:14

    You should be currently using the jquery deferred objects.

    0 讨论(0)
  • 2021-01-16 03:30

    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);
    
    0 讨论(0)
提交回复
热议问题