多个ajax请求完成后触发回调 [英] Firing callback after multiple ajax requests are complete
问题描述
loadInfo: function(){
var jsonCounter = 0,
room = ['room1','room2','room3'],
dates = [],
prices = []
$.each(booking.rooms, function(key, room_name) {
$.getJSON('/get_info.php?room='+room_name, function(data) {
dates[room_name] = data
jsonCounter++
})
$.getJSON('/get_info.php?room='+room_name+'&prices', function(data) {
prices[room_name] = data
jsonCounter++
})
})
function checkIfReady() {
if (jsonCounter === rooms.length * 2) {
clearInterval(timer)
run_the_rest_of_the_app()
}
}
var timer = setInterval(checkIfReady, 100)
}
(修改了很多,因为它是类等的一部分)
(Modified a lot, as it's part of a class etc etc.)
目前这感觉有点hackish,因为定时器的使用看起来很垃圾.我会使用 $.when 和 $.done,但我不知道可能有多少个房间,所以我不知道什么时候放.
At the moment this feels a bit hackish, as the timer usage seems rubbish. I would use $.when and $.done, but I don't know how many rooms there might be, so I don't know what to put into when.
如何确保 run_the_rest_of_the_app() 仅在所有 AJAX 请求返回后才被调用?
How do I ensure that run_the_rest_of_the_app() only gets called once all of the AJAX requests come back?
推荐答案
var activeAJAX = 0;
在进行 AJAX 调用之前,
activeAJAX++;
Before making an AJAX call,
activeAJAX++;
完成 AJAX 调用后(在回调中):
if (--activeAJAX == 0) { allDone();}
After completing an AJAX call (in the callback):
if (--activeAJAX == 0) { allDone(); }
这篇关于多个ajax请求完成后触发回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!