2011-05-09 28 views
1
$(document).ready(function() { 
    $("#list1").jqGrid({ 
     url: 'example1.php', 
     /*balabala...*/ 
     gridComplete: function() { 

     } 
    }); 

    $("#list2").jqGrid({ 
     url: 'example2.php', 
     /*balabala...*/ 
     gridComplete: function() { 

     } 
    }); 

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

我應該怎麼辦?謝謝!如何確認何時完成多個AJAX呼叫?

回答

3

最簡單的方法是把你的gridComplete回調「東西」,但有兩個回調檢查另一個已完成。沿着這些路線的東西:

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 
}); 

這很好地延伸到兩個以上的列表與幾個小的修改:

  • 使用var how_many_done = 0;代替one_done
  • 做一個++how_many_done;,而不是one_done = true;並將其移動到的done_checker頂部。
  • 更換if(one_done)if(how_many_done == number_of_tasks)其中number_of_tasks是你有多少AJAX任務都有。

普通版看起來有點像這樣:

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(); 
    } 
} 

一個更好的版本將在一個封閉包的狀態:

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

這是真棒,人 – Cynial 2011-05-09 05:01:47

+0

@Cynial:我補充說,隔離額外狀態另一個更新,它可能是一個有點多,但。 – 2011-05-09 05:04:36

+0

不要這樣說,它真的幫助我! :) – Cynial 2011-05-09 05:18:10