[英]jQuery run function after $.each ajax request has completed
我在ECMA6中使用Promises
使用了一个简单的脚本,但是现在我正在将写给jQuery的内容转换为对所有浏览器都兼容,但是我遇到的问题是availableDevices
包含AJAX响应数组,而不是诸如产品名的数组脚本告诉它。
基本上,当$ .each内的所有AJAX请求都完成时,我需要使用该数据运行一个函数。 我想念什么? (自从我用jQuery编写任何东西以来已经有一段时间了...)
var availableDevices = [];
$.each(products, function (index, product) {
availableDevices.push($.ajax({
type: 'GET',
url: 'http://localhost:1337/api/product_availability?__url_path_param=' + formatProductName(product.product_name),
complete: function (response) {
if (response.status == 200) {
return formatProductName(product.product_name);
}
}
}));
});
$.when(availableDevices).then(function (data) {
console.log(data);
});
无需将每个调用的结果存储在单独的数组中,您可以通过then
方法访问每个响应:
var requests = [];
$.each(products, function (index, product) {
requests.push($.ajax({
type: 'GET',
url: 'http://localhost:1337/api/product_availability?__url_path_param=' + formatProductName(product.product_name)
}));
});
$.when.apply($, requests).then(function() {
console.log(arguments.length + " results returned");
for(var i=0;i<arguments.length;i++){
var arg = arguments[i];
console.log(arg);
}
});
实时示例(使用jsfiddle json回显进行演示): http : //jsfiddle.net/vzq4Lwm8/
阅读您的评论后,有一个更好的解决方案,将$.Deferred()
和$.ajax
调用中的complete
函数结合使用:
var deferreds = $.map(products, function (product) {
var formattedProduct = formatProductName(product)
var defer = $.Deferred();
$.ajax({
type: 'GET',
url: 'http://localhost:1337/api/product_availability?__url_path_param=' + formattedProduct,
complete: function (response) {
if (response.status == 200) {
defer.resolve(formattedProduct);
}
else{
defer.resolve(null);
}
}
})
return defer;
});
$.when.apply($, deferreds).then(function() {
console.log(arguments.length + " results returned");
var availableProducts = $.map(arguments, function(x) { return x });
// availableProducts will only contain items which returned 200 response
});
现场演示: http : //jsfiddle.net/vzq4Lwm8/1/
在为$.when
提供数组时,您对$.when
调用语法不正确。 同样,使用这种模式时,您将必须将所有响应合并在一起, then()
在then()
处理函数中使用它。 像这样:
var requests = [];
var data = [];
$.each(products, function (index, product) {
requests.push($.ajax({
type: 'GET',
url: 'http://localhost:1337/api/product_availability?__url_path_param=' + formatProductName(product.product_name),
success: function (response) {
// note you're not actually using the `response` var here at all...?
return data.push(formatProductName(product.product_name));
}
}));
});
$.when.apply($, availableDevices).then(function() {
console.log(data);
});
jQuery $.ajax()
可以使用一个success
参数,当ajax
请求成功完成时调用该函数,如您在文档中所见
因此,您的代码应为:
$.each(products, function (index, product) {
availableDevices.push($.ajax({
type: 'GET',
url: 'http://localhost:1337/api/product_availability?__url_path_param=' + formatProductName(product.product_name),
complete: function (response) {
if (response.status == 200) {
return formatProductName(product.product_name);
}
},
success:function(){ }
}));
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.