双ajax请求响应

时间:2016-06-20 12:26:09

标签: javascript jquery ajax

我正在使用ajax successives请求,我需要在所有成功请求完成后进行回调

u

使用此代码,在调用" exemple2.php"之前调用done函数。成功了。

我怎么能等待呢?

感谢您的回答!

3 个答案:

答案 0 :(得分:1)

function doAjaxRequest(data, id) {
    // Get payment Token
    return new Promise(function(resolve,reject){
        $.ajax({
        type: "POST",
        url: 'exemple1.php',
        data: data
        success: function(msg){
            $.ajax({
                type: "POST",
                url: 'exemple2.php',
                data: msg,
                success: function(msgr) {
                    document.getElementById(id).value=msgr;
                    resolve();
                },
                error:function (xhr, status, error) {
                    //Do something
                    reject();
                }
            });
        },
        error:function (xhr, status, error) {
            //Do something
            reject();
        }
    });
    });
}



Promise.all([
    doAjaxRequest(data, "input-1"),
    doAjaxRequest(otherData, "input-2")])
.then(function(values){
    //Need do something when both second ajax requests (example2.php) are finished
}

答案 1 :(得分:1)

你的sub ajax请求独立于第一个ajax结果,然后对example2的调用与$ .when()promise.abort完全分开 只是尝试使用jquery $ .ajax返回promise这样的事实 这是我的代码来自plnkr

// Code goes here
function doAjaxRequest(data, id) {
    // Get payment Token
    return $.ajax({
        type: "GET",
        url: 'example1.json',
        data: data
    }).then(function(msg, status, jqXhr) {
      return $.ajax({
          type: "GET",
          url: 'example2.json',
          data: msg
      });
    }).done(function(msgr) {
        console.log(msgr);
        return msgr;
    });
}

var data = {foo:'bar'};
var otherData = {foo2:'bar2'};

$.when(
    doAjaxRequest(data, "input-1"),
    doAjaxRequest(otherData, "input-2")
).done(function(a1, a2) {
    console.log(a1, a2);
    //Need do something when both second ajax requests (example2.php) are finished
});

注意,我用GET替换POST并在plnkr上使用exampleX.json文件进行测试

您可以在此处进行测试:https://plnkr.co/edit/5TcPMUhWJqFkxbZNCboz

答案 2 :(得分:0)

返回自定义延迟对象,例如:

function doAjaxRequest(data, id) {
    var d = new $.Deferred();
    // Get payment Token
    $.ajax({
        type: "POST",
        url: 'exemple1.php',
        data: data
        success: function(msg){
            $.ajax({
                type: "POST",
                url: 'exemple2.php',
                data: msg,
                success: function(msgr) {
                    document.getElementById(id).value=msgr;
                    d.resolveWith(null, [msgr]); // or maybe d.resolveWith(null, [msg]);
                },
                error:function (xhr, status, error) {
                    //Do something
                    d.reject();
                }
            });
        },
        error:function (xhr, status, error) {
            //Do something
            d.reject();
        }
    });
    return d;
}

现在,我不确定您传递给$.when().done()回调的预期数据是什么。