我有以下代码,使用 AJAX 从几个不同的 URL 中提取 JSON 数据,我想将它们存储到单独的数组中。这是一个示例:
var var1 = $.ajax({
url: FEED1,
dataType: 'jsonp',
crossDomain: true,
success: function (data) {
if (data) {
ItemAry1 = data.posts;
}
}
});
var var2 = $.ajax({
url: FEED2,
dataType: 'jsonp',
crossDomain: true,
success: function (data) {
if (data) {
ItemAry2 = data.posts;
}
}
});
在我的代码中我有几个这样的。每个数组具有完全相同的数据的问题。甚至 FEED1 和 FEED2 也是不同数据的 URL。
最佳答案
创建一个函数!
var serviceURL = "http://www.example.com";
var itemArrays = {};
function getFeed(category_id){
return $.ajax({
url: serviceURL,
data: {
"json":"get_category_post",
"category_id":category_id,
"count": 25
},
dataType: 'jsonp',
crossDomain: true,
success: function (data) {
if (data) {
itemArrays[i] = data.posts;
}
}
});
}
var feedPromises = [];
for (var i = 0, count = 9; i < count; i++){
//start the process to get all the feeds and save their ajax promises into an array
feedPromises.push(getFeed(i));
}
// wait until all the feeds return data to continue
$.when.apply(this, feedPromises)
.done(function(){
// when all the data calls are successful you can access the data via
itemArrays[0];
itemArrays[1];
console.log(itemArrays);
});
关于jquery - 处理多个 AJAX 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28121153/