在完成多个ajax事件时调用函数

时间:2015-08-27 12:08:36

标签: javascript jquery ajax

所以说我有多个ajax请求通过父函数同时触发。每个ajax函数都有一个单独的单独完成函数,它们彼此无关。如果我想在完成所有ajax函数后执行另一个函数,但是在每个单独的ajax函数中指定完成函数之后,我将如何进行此操作?

function ajax1(str) {
    return $.ajax({
        type: 'get',
        data: "q=" + str,
        url: 'foo.php',
        success: function (result) {
            //success!
        }

    },
    complete: function (data) {

        function ajaxcomplete1();
    },

    )
};

function ajax2(str) {
    return $.ajax({
        type: 'get',
        data: "q=" + str,
        url: 'foo.php',
        success: function (result) {
            //success!
        }

    },
    complete: function (data) {

        function ajaxcomplete2();
    },

    )
};

function ajaxcall() {
    ajax1();
    ajax2();
}

function allajaxcomplete() {
    // some code to be executed on completion of all ajax requests but after individual "ajaxcomplete1" and "ajaxcomplete2" functions
}
ajaxcall();
allajaxcomplete();

1 个答案:

答案 0 :(得分:5)

$.ajax返回jQuery Deferred object(承诺)。然后,当所有这些承诺得到解决时,您只需使用$.when来调用函数:

function ajax1(str) {
    return $.ajax({
        type: 'get',
        data: "q=" + str,
        url: 'foo.php',
        success: function (result) {
            //success!
            ajaxcomplete1();
        }
    });
};

function ajax2(str) {
    return $.ajax({
        type: 'get',
        data: "q=" + str,
        url: 'foo.php',
        success: function (result) {
            //success!
            ajaxcomplete2();
        }
    });
};

function ajaxcall() {
    // store the promises (for clarity, you also could call the functions directly in the when)
    var d1 = ajax1(),
        d2 = ajax2();

    // this function will be called only when both promises d1 and d2 are resolved
    $.when(d1, d2).done(function(result1, result2){
        // do stuff when both functions are done
        // result1 and result2 are the result of the ajax calls inside your functions

        allajaxcomplete();
    });
}