在具有延迟的循环内向阵列添加新对象

时间:2015-06-13 06:45:33

标签: javascript jquery arrays ajax

我有一个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;
})();

2 个答案:

答案 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);

itotalPages时,这将停止。

答案 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);
    }
})();

喜欢这个吗?