我有一个for
循环需要进行AJAX
调用,迭代之间有一秒钟的延迟。它应该抓住对象并.push
到数组上。下面的代码只添加第一个对象。我做错了什么?
var maxLoops = 10;
var counter = 0;
(function processPages() {
if(counter++ >= maxLoops) return;
setTimeout(function() {
//check page count and loop. push all new objects into allProducts
for (var i=1; i <= totalPages; i++){
$.ajax({ url: '/process.php',
data: {category: 'sportingGoods', page: i},
type: 'post',
success: function(output) {
allProducts.push(output);
}
})
}
}), 1000;
})();
答案 0 :(得分:3)
如果你想做几个ajax调用并在它们之间等待,你可以这样做:
(function processPages(i) {
if (i===totalPages) {
// all the pages have been fetched, you may
// use the allProducts array here
return;
}
$.ajax({ url: '/process.php',
data: {category: 'sportingGoods', page: i},
type: 'post',
success: function(output) {
allProducts.push(output);
setTimeout(processPages, 1000, i+1);
}
})
})(0);
当i
为totalPages
时,这将停止。
答案 1 :(得分:0)
var maxLoops = 10;
var counter = 0;
(function processPages() {
if (counter++ >= maxLoops) return;
for (var i = 1; i <= totalPages; i++) {
setTimeout(function () {
//check page count and loop. push all new objects into allProducts
$.ajax({
url: '/process.php',
data: {category: 'sportingGoods', page: i},
type: 'post',
success: function (output) {
allProducts.push(output);
if(allProducts.length === totalPages){
// call final function - array filled
}
}
})
}, 1000 * i);
}
})();
喜欢这个吗?