2014-11-14 37 views
0

我需要做兩個異步(需要第二次調用只有當某些條件爲真)調用,並且當兩個調用都返回數據時,我需要再次調用。爲此,我決定使用jquery $ when。

在我做第二個Ajax調用之前,我需要檢查一些條件。如果它是真的,那麼我需要進行第二次Ajax調用,否則不需要進行第二次Ajax調用。

這裏是僞代碼

$.when($.get(url, function (result, status, xhr) { 
     myresult = result; 
    })), 
    (
     //If XYZ === 10 
      //Make second Ajax call only if condition is true 

    ).then(function (r1, r2) { 
     //DO something 

    }); 

我怎樣才能做到這一點?使用Jquery或任何其他庫?

+2

您的描述似乎矛盾。首先,「我需要進行兩個異步調用,當兩個調用都返回數據時,我需要再次調用」,然後您說第二個調用僅基於第一個調用的結果。你能澄清你在問什麼嗎?順便說一句,答案是肯定的 - 你可以使用jQuery來實現。 –

+0

@Colin:我只有在某些條件爲真時才需要進行第二次Ajax調用。如果我正在撥打第二個電話,那麼只有當我從這兩個電話收到數據時,我纔會進行最後的通話。 – SharpCoder

回答

0

兩個ajax請求成功後執行一個函數。

$.when($.ajax("/page1.php"), $.ajax("/page2.php")).done(function(a1, a2) { 

    //if both the calls are sucess then only you can reach here. 
    // inside this you can make your third ajax call. 

    } 
}); 
+2

在這種情況下,我不需要使用'$ when'。我可以進行Ajax調用並取得成功,如果需要(根據某些條件),我可以調用第二次Ajax調用。 – SharpCoder

+0

我已更新代碼,可能會對您有所幫助。 – KanhuP2012

0
var first = $.ajax(...); 
var second = (condition) ? $.ajax(...) : $.Deferred().resolve(); // ajax only on condition 

$.when(first, second).then(function(res1, res2){ 
    // work with res1 and res2, res2 is undefined if no call was made 
}); 
0

您可以使用三元運算符的第二個Ajax調用。如果條件爲假,則將null值作爲第二個參數$.when

這裏是僞代碼

$.when(
    //first ajax call , 
    (XYZ===10) ? //second ajax call 
       : null 
     ).then(function (r1, r2) { 
     //DO something 

    }); 

希望它能幫助。

演示: - jsfiddle.net/NF2jz/5721(嘗試一個= 0和a = 1)

+0

這不起作用。 –

+0

@VladislavDimitrov看到這個演示。 http://jsfiddle.net/NF2jz/5721/將a的值更改爲1,並根據第二個請求更新文本。 – yajiv