处理多个AJAX调用

时间:2015-01-24 01:00:25

标签: jquery ajax promise

我有以下代码使用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都是不同数据的网址。

2 个答案:

答案 0 :(得分:2)

制作一个功能!

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);
    });

答案 1 :(得分:1)

这是我最终使用的感谢@Patrick Gunderson:

function get_articles(category_id) {
        console.log('running ' + category_id);

        var url_addition = "?json=get_category_posts&category_id=" + (category_id + 1);
        var url_count = "&count=25";
        var serviceURL = "http://www.example.com/" + url_addition + url_count;

        console.log(serviceURL);

        return $.ajax({
            url: serviceURL,
            dataType: 'jsonp',
            crossDomain: true,
            success: function (data) {
                if (data) {
                    itemArrays[category_id] = data.posts;
                }
                else{
                    console.log("Failed category_id: "+ category_id);
                }
            }
        });
    }

    var feedPromises = [];
    for (var i = 0, count = 10; i < count; i++) {
        //start the process to get all the feeds and save their ajax promises into an array
        feedPromises.push(get_articles(i));
    }
    $.when.apply(this, feedPromises)
        .done(function () {
            // when all the data calls are successful you can access the data via
            console.log(itemArrays);
        });

    console.log(feedPromises);