如何确认何时完成多个AJAX通话?

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

我应该怎么做 ? 谢谢!

最简单的方法是将你的“东西”放在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(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); 

您当前应该使用jquery延迟对象 。