我使用一个获取参数的方法作为 JavaScript Controller 的初始化。根据参数的值,我使用 $.when() 和 then() 方法从 ajax 调用获取数据。
具体来说,$ 中传递的参数是否为 true。当我想要 4 个 ajax 调用,否则需要 3 个。
$.when(
$.ajax({
url: "test.html"
}).done(function () {
$(this).addClass("done");
}),
$.ajax({
url: "test2.html"
}).done(function () {
$(this).addClass("done");
}),
$.ajax({
url: "test3.html"
}).done(function () {
$(this).addClass("done");
}),
if (config,EditMode) {
$.ajax({
url: "test3.html"
}).done(function () {
$(this).addClass("done");
})
}
).then(function () {
if (config,EditMode)
somemethod();
else
someOtherMethod();
}).done(function () {
//code
});
我尝试了类似上面的方法,但我无法真正使语法工作。 当然,我可以创建一个全局的 if else 并复制代码。 但我会收到有关 DRY 原则的投诉:))。
你有什么想法吗? 谢谢
最佳答案
请勿将 $.ajax
调用直接作为参数调用 $.when()
。
更简单的方法是创建一个包含各个 Promise 的数组:
var promises = [];
promises.push($.ajax(...));
promises.push($.ajax(...));
promises.push($.ajax(...));
if (config.EditMode) {
promises.push($.ajax(...));
}
然后使用.apply
传递列表:
$.when.apply($, promises).then(...);
当您事先不知道要传递多少参数时,这是调用函数的常见方法。
关于javascript - 如何在 jQuery 中的 $.when().then() 中使用 If 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49531089/