[英]Applying condition to jQuery.when() deferred functions
我想對$.when()
函數中的每個延遲請求應用條件(在發出請求之前)。 但是,在$.when
放置if
條件會返回錯誤。
什么是做我基本上描述的波紋管的正確方法?
$.when(
if(var1) {
$.getJSON(url1, function(data) {...}),
},
if(var2) {
$.getJSON(url2, function(data) {...}),
},
if(varN) {
$.getJSON(urlN, function(data) {...}),
},
).then(function() {
...
});
您可以簡單地構造一個AJAX Promise數組。 之后,使用$.when.apply($, <yourArray>)
。 為了說明解決方案,以下是基於您提供的代碼的示例:
// Construct array to store requests
var requests = [];
// Conditionally push your deferred objets into the array
if(var1) requests.push($.getJSON(url1, function(data) {...}));
if(var2) requests.push($.getJSON(url2, function(data) {...}));
if(var3) requests.push($.getJSON(url3, function(data) {...}));
// Apply array to $.when()
$.when.apply($, requests).then(function() {
// Things to do when all is done
});
請記住,這是一個顯示概念驗證示例的代碼片段:我正在使用JSONPlaceholder返回的偽JSON:
$(function() { // Construct array to store requests var requests = []; // Conditional vars var var1 = true, var2 = false, var3 = true; // Conditionally push your deferred objets into the array if (var1) requests.push($.get('https://jsonplaceholder.typicode.com/posts/1', function(data) { return data; })); if (var2) requests.push($.get('https://jsonplaceholder.typicode.com/posts/2', function(data) { return data; })); if (var3) requests.push($.get('https://jsonplaceholder.typicode.com/posts/3', function(data) { return data; })); // Apply array to $.when() $.when.apply($, requests).then(function(d) { // Log returned data var objects = arguments; console.log(objects); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
您可以在$ when()中使用三元運算符。 下面的代碼為我工作:
var includeX = true, includeY = false;
var x = $.get('check.html');
var y = $('div').animate({height: '200px'}, 3000).promise(); // you may use an ajax request also here
$.when(includeX ? x : '', includeY ? y: '').done(function(){
console.log(x);
console.log(y);
console.log('done');
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.