2014-09-05 25 views
0

This post answered the question I was about to ask。唯一的問題是我需要使用第一個調用的結果作爲第二個Ajax調用的參數。jquery Ajax:如何使用第一個ajax的結果調用第二個調用? (.then(function()))

事實上,我需要爲某個客戶獲得聯繫。但是,我唯一的論點是來自該客戶的請求。我想先打電話來獲取客戶端的客戶端號碼,然後使用該ID來查詢所有聯繫人。

有人可以提供一個小代碼其中第一個查詢的結果是用來進行第二次調用嗎?

這裏是他寫的部分代碼。

$.ajax({..}) // Promise 1 
.then(function() { 
    // This will only fire if the first request had no error - was "done" 
    // We then return a NEW promise for the 2nd request. In a proper 
    // Promises/A, 'then' returns a (new) promise. 
    return $.ajax({..}) // Promise 2 
}) 

感謝您的幫助。

+2

呃... ...這是在傳遞給你。然後回調的第一個參數... – 2014-09-05 20:30:34

+0

@KevinB,我不是太阿賈克斯familliar。我剛剛在第一個電話裏面打了另一個電話,但我認爲這應該是最好的方式。你能提供一個樣本,我該怎麼做? – Richard77 2014-09-05 20:32:50

回答

0

.then回調包含承諾的結果。在這種情況下,它將包含三個參數,與傳遞給$.ajax成功回調的相同三個參數:解析結果,文本狀態和jqXHR對象。

$.ajax({..}) // Promise 1 
.then(function (result, status, jqXHR) { 
    // This will only fire if the first request had no error - was "done" 
    // We then return a NEW promise for the 2nd request. In a proper 
    // Promises/A, 'then' returns a (new) promise. 
    console.log(result); 
    return $.ajax({..}) // Promise 2 
}).done(function (contacts, status, jqXHR) { 
    //... 
}); 

您可以使用result從響應中獲取客戶ID。最後的.done將被第二個承諾的響應觸發。

+0

.then函數中的結果是否與第一個ajax調用返回的結果相同? – Richard77 2014-09-05 20:42:41

+0

是的,它是一樣的。 – 2014-09-05 20:48:18

0

會這樣的工作嗎?

function getContacts(data){ 
    $.ajax({ 
     type: 'POST', 
     dataType: dataType, 
     url: 'someotherUrl', 
     data: idofclient = data.idofclient 
     success: function(data){ 
      console.log(data.contact); 
     } 
    }); 
} 

$.ajax({ 
    type: 'POST', 
    dataType: dataType, 
    url: 'someUrl', 
    success: function(data){ 
     getContacts(data); //data should have the id of the client of course 
    } 
}); 
+0

我想這應該可行,但我認爲這並不像我使用過的那樣簡潔。然而,我認爲它應該沒問題。 – Richard77 2014-09-05 20:41:24

+0

啊,我不知何故錯過了.then(函數() - 你的問題的一部分。) – aolsen 2014-09-05 20:45:35

1
$.ajax({...}).then(function (d1) { 
    // d1 is the data returned from the first ajax call. 
    // You can use it as a parameter to the second ajax call below. 
    return $.ajax({...}).done(function (d2) { 
     // d2 is the data returned from the second ajax call. 
     console.log(d1, d2); 
    }) 
}); 
+0

這更像它。我正在嘗試它。 – Richard77 2014-09-05 20:44:38

相關問題