Hai*_*vgi 14 javascript ajax jquery wait
我的文档中有一些ajax调用.ready()
喜欢 :
for (j=1; j <= 7; j++){
(function(index) {
$.getJSON('my.php', {id:index},
function(data) {
$.each(data, function(index2, array){
........
});
});
})(j)
}
//DO NOT CONTINUE UNTIL FINISH AJAX CALLS
........
MORE JQUERY CODE
Run Code Online (Sandbox Code Playgroud)
我怎么能强迫它等待而不是继续,直到我们从ajax请求得到所有回调?
san*_*ino 16
我根本不喜欢任何答案,最好的方法(因为Jquery 1.5+)是使用Deferred对象,那些是操作异步调用的对象,你可以解决:
$.when($.ajax("/page1.php"), $.ajax("/page2.php"))
.then(myFunc, myFailure);
Run Code Online (Sandbox Code Playgroud)
这样,myFunc在进行2次ajax调用后执行,而myFailure如果有任何一次出错则执行.
您可以在jquery官方文档中阅读更多相关信息:JQuery Deferred Object
我写这个解决方案如果有人看到这篇文章可能会有所帮助.
对不起我的英文:P
首先,您可能需要考虑在一次调用中执行启动代码.
第二:而不是等待只是调用另一个函数调用.对于上面的代码,它应该看起来像:
for (j=1; j <= 7; j++){
(function(index) {
$.getJSON('my.php', {id:index},
function(data) {
$.each(data, function(index2, array){
........
});
if (j === 7) {
initDoneDoMoreStuff()
}
});
})(j)
}
Run Code Online (Sandbox Code Playgroud)
或触发:
for (j=1; j <= 7; j++){
(function(index) {
$.getJSON('my.php', {id:index},
function(data) {
$.each(data, function(index2, array){
........
});
if (j === 7) {
$(document).trigger("initdone");
}
});
})(j)
}
$(document).bind("initdone", function() {....});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19259 次 |
| 最近记录: |