2016-06-20 2 views
1

Я использую Ajax successives запросы, и мне нужно сделать обратный вызов, когда все запросы successives сделаныДвойной ответ на запрос Ajax

function doAjaxRequest(data, id) { 
    // Get payment Token 
    return $.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; 
       }, 
       error:function (xhr, status, error) { 
        //Do something 
       } 
      }); 
     }, 
     error:function (xhr, status, error) { 
      //Do something 
     } 
    }); 
} 

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

С помощью этого кода, проделанная функция вызова перед моими вызовами «exemple2. php ".

Как я могу подождать?

Спасибо за ответ!

ответ

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 
} 
+0

Исправьте меня, если я ошибаюсь, но IE не поддерживает его, не так ли? –

+0

https://api.jquery.com/category/deferred-object/ поддерживается IE, с той же логикой. Спасибо! – Bouffe

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() обратного вызова.

1

Ваш запрос суб Аякс является независим от первого результата AJAX, то вызов example2 полностью отделен от $ .when() promise.abort Просто попробуйте использовать тот факт, что возвращение JQuery $ .ajax обещаю как объект вот мой код из 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 
}); 

Внимание, я заменяю POST на GET и использовать exampleX.json файлы для моих тестов на plnkr

Вы можете проверить его здесь: https://plnkr.co/edit/5TcPMUhWJqFkxbZNCboz

Смежные вопросы