gpt4 book ai didi

javascript - 传递一个向 $.when .done 发出 ajax 请求的函数

转载 作者:行者123 更新时间:2023-11-30 18:32:33 25 4
gpt4 key购买 nike

我想即时生成 ajax 请求,但我想确保在它们全部完成后得到回调,所以我想将它们包装在 .when .done 语句中,如下所示:

$.when(function(){
$.each(oOptions, function(){
var filePath = this.filePath,
dataType = this.dataType;

$.ajax({
url : filePath,
dataType : dataType
});
});
})
.done(function(){
console.log('success');

console.log(arguments);
})
.fail(function(){
console.log('failed');
});

我的选项是一个对象数组,其中包含我想同时发出的每个 ajax 请求的文件路径和数据类型。此代码将返回成功,但参数只是一个函数,ajax 请求永远不会通过。关于如何做到这一点有什么想法吗?

最佳答案

您将函数传递给 $.when,同时您应该传递一个或多个 Deferred。您可以用 deferred 填充一个数组并将其作为参数传递给 $.when:

var deferreds = [];

$.each(oOptions, function() {
var filePath = this.filePath,
dataType = this.dataType;

deferreds.push($.ajax({
url : filePath,
dataType : dataType
}));
});

// use the array elements as arguments using apply
$.when.apply($, deferreds)
.done(function(){
console.log('success');

console.log(arguments);
})
.fail(function(){
console.log('failed');
});

关于javascript - 传递一个向 $.when .done 发出 ajax 请求的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9196181/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com