我想在$.when()
函数中(在发出请求之前)对每个延迟请求应用一个条件。但是,在if
中放置$.when
条件会返回错误。
做什么是我实质上描述的正确方法?
$.when(
if(var1) {
$.getJSON(url1, function(data) {...}),
},
if(var2) {
$.getJSON(url2, function(data) {...}),
},
if(varN) {
$.getJSON(urlN, function(data) {...}),
},
).then(function() {
...
});
答案 0 :(得分:3)
您可以简单地构造一个AJAX承诺数组。之后,使用$.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);
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
答案 1 :(得分:-2)
您可以在$ 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');
})