weixin_33674976 2015-01-24 01:00 采纳率: 0%
浏览 19

处理多个AJAX呼叫

I have the following code using AJAX to pull JSON data from a few different URLs and I want to store them into separate arrays. Here is a sample:

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

In my code I have several of these. The issue that each array has the same exact data. Even the FEED1 and FEED2 are urls to different data.

  • 写回答

2条回答 默认 最新

  • ℡Wang Yan 2015-01-24 01:06
    关注

    make a function!

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

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料