$(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(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);
关于ajax - 如何确认多个 AJAX 调用已完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5932432/