加载所有ajax时回调

时间:2014-12-15 13:09:21

标签: jquery ajax

我有这个代码

var chapterNameArr = ['firstchapter','secondchapter','thirdchapter','fourthchapter','fifthchapter','sixthchapter','seventhchapter']; 


$.each(chapterNameArr, function( index, value ) {

    var $chapterCont = $("#"+value);

    $.ajax({
      url: "scripts/templates/"+value+".html",
      cache: false,
      success: function(data){
        var $data = $(data);
        $chapterCont.append($data);
      }
    });

});

我想在成功加载来自ajax调用的所有内容时执行一个函数。我该怎么做?

2 个答案:

答案 0 :(得分:2)

完成多个请求后调用回调的正确方法是使用jQuery $ .when函数:

http://api.jquery.com/jquery.when/

我真的建议你仔细阅读有关此功能的文件 并且推迟了#39;概念(http://api.jquery.com/Types/#Deferred

应该是这样的(仅作为一个例子)

var chapterNameArr = ['firstchapter','secondchapter','thirdchapter','fourthchapter','fifthchapter','sixthchapter','seventhchapter']; 
var pendingAjax = []

$.each(chapterNameArr, function( index, value ) {

    var $chapterCont = $("#"+value);

    var ajax = $.ajax({
      url: "scripts/templates/"+value+".html",
      cache: false,
      success: function(data){
        var $data = $(data);
        $chapterCont.append($data);
      }
    });

    pendingAjax.push(ajax)
});

$.when.apply($, pendingAjax).done( successCallback ).fail( failCallback)

答案 1 :(得分:0)

$。active返回活动Ajax请求的数量。使用$ .active == 0表示没有ajax请求处于活动状态。您还可以使用ajaxStart和ajaxStop来跟踪请求何时处于活动状态

代码:

var ajaxRequestsTimer = setInterval(isAjaxRequestsCompleted, 10000);

function isAjaxRequestsCompleted(){
    if($.active == 0) {
        clearInterval(ajaxRequestsTimer);
        $(document).trigger('ajaxRequestsCompleted');
    }
}

$(document).on('ajaxRequestsCompleted',function(){
    // insert the code here to execute after all ajax requests completed

})