[英]Making conditional Async calls using Jquery $when
我需要進行兩個異步( 僅當某些條件為true時才需要進行第二次調用 )調用,並且當兩個調用都返回數據時,我需要進行另一個調用。 為此,我決定使用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或任何其他庫?
在兩個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.
}
});
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
});
您可以使用三元運算符進行第二個ajax調用。 如果condition為false,則將null
值作為$.when
第二個參數傳遞。
這是偽代碼
$.when(
//first ajax call ,
(XYZ===10) ? //second ajax call
: null
).then(function (r1, r2) {
//DO something
});
希望能幫助到你。
演示: -jsfiddle.net/NF2jz/5721 (嘗試a = 0和a = 1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.