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)
}
(经过修改,因为它是课程的一部分等等)。
目前这感觉有点hackish,因为计时器使用似乎是垃圾。我会使用$ .when和$ .done,但我不知道可能有多少房间,所以我不知道在什么时候投入。
如果所有AJAX请求都回来后,我如何确保只调用run_the_rest_of_the_app()?
答案 0 :(得分:19)
var activeAJAX = 0;
在进行AJAX通话之前,activeAJAX++;
完成AJAX通话后(在回调中):if (--activeAJAX == 0) { allDone(); }
答案 1 :(得分:4)
这是如何使用/ done
loadInfo: function(){
var room = ['room1','room2','room3'],
dates = [],
prices = [],
requests = [];
$.each(booking.rooms, function(key, room_name) {
var aRequest;
aRequest = $.getJSON('/get_info.php?room='+room_name, function(data) {
dates[room_name] = data;
});
requests.push(aRequest);
aRequest = $.getJSON('/get_info.php?room='+room_name+'&prices', function(data) {
prices[room_name] = data;
});
requests.push(aRequest);
})
$.when.apply($, requests).done(run_the_rest_of_the_app);
}