如何编写等待3个不同ajax请求响应的事件驱动代码?

Kim*_*cks 0 javascript ajax jquery callback

我有一个网页,我有3个单独的ajax调用

所有3使用相同的结构:$ .ajax({//这是处理数据和发送邮件url的urp文件:url,

        //POST method is used
        type: "POST",

        //pass the data         
        data: data,     

        //Do not cache the page
        cache: false,

        //success
        success: function (json) {              
Run Code Online (Sandbox Code Playgroud)

我想触发另一个函数,但只有3个单独的ajax调用成功.

我该怎么做呢?

更新:使用$ .when()时我现在遇到问题

我的代码现在看起来像这样:

function mainFunction() {
    $.when(someAjaxCall()).done(function(ajaxResult){
            // after all the pages, covers, and sneaks are uploaded
            // we will now change the status
            //start the ajax
            console.log(ajaxResult);
}

function someAjaxCall() {
    // do something...
    if (someGlobalScopedVariable == true) {
         return $.ajax({
        //this is the php file that processes the data and send mail
        url: url,

        //POST method is used
        type: "POST",

        //pass the data         
        data: data,     

        //Do not cache the page
        cache: false,

        //success
        success: function (json) {....},
     });
    }
}
Run Code Online (Sandbox Code Playgroud)

mainFunction $ .when中的ajaxResult给了我undefined.我做错了什么因为我跟着这个http://api.jquery.com/jQuery.when/

Nat*_*all 8

使用jQuery.when.

var deferred1 = $.ajax({ ... });
var deferred2 = $.ajax({ ... });
var deferred3 = $.ajax({ ... });

$.when(deferred1, deferred2, deferred3).then(
    function(info1, info2, info3) {
        var response1 = info1[0], response2 = info2[0], response3 = info3[0];
        // Do something with response 1, 2, and 3...
    }
);
Run Code Online (Sandbox Code Playgroud)

$.ajax返回一个Deferred对象.您可以传递多个Deferred对象$.when,以便等待所有对象完成.