9
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)

}

(修改了很多,因为它是类等的一部分等)

目前这感觉有点骇人听闻,因为计时器的使用似乎很垃圾。我会使用 $.when 和 $.done,但我不知道可能有多少个房间,所以我不知道什么时候放什么。

如何确保 run_the_rest_of_the_app() 仅在所有 AJAX 请求返回后才被调用?

4

2 回答 2

19
  • var activeAJAX = 0;

  • 在进行 AJAX 调用之前,activeAJAX++;

  • 完成 AJAX 调用后(在回调中):if (--activeAJAX == 0) { allDone(); }

于 2012-04-09T15:29:56.533 回答
4

这是何时/完成的使用方法

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);
}
于 2012-04-09T15:37:33.340 回答