我有以下代码使用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);
    });

07-24 18:47
查看更多