Ajax:使用for循环调用多个API

时间:2016-05-09 08:25:12

标签: jquery ajax

由于我需要调用数据的早午餐来制作图表,我需要调用10个或更多不同的API,所以我创建了这样的函数

function trend1() {
  return $.ajax({
    url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile0").html(), //getting the api
    type: 'get',
    success: function(data) {

    }
  });
}

function trend2() {
  return $.ajax({
    url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile1").html(), //getting the api
    type: 'get',
    success: function(data) {

    }
  });
}

function trend3() {
  return $.ajax({
    url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile2").html(), //getting the api
    type: 'get',
    success: function(data) {

    }
  });
}

function trend4() {
  return $.ajax({
    url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile3").html(), //getting the api
    type: 'get',
    success: function(data) {

    }
  });
}

function trend5() {
  return $.ajax({
    url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile4").html(), //getting the api
    type: 'get',
    success: function(data) {

    }
  });
}

function trend6() {
  return $.ajax({
    url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile5").html(), //getting the api
    type: 'get',
    success: function(data) {

    }
  });
}

function trend7() {
  return $.ajax({
    url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile6").html(), //getting the api
    type: 'get',
    success: function(data) {

    }
  });
}

function trend8() {
  return $.ajax({
    url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile7").html(), //getting the api
    type: 'get',
    success: function(data) {

    }
  });
}

function trend9() {
  return $.ajax({
    url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile8").html(), //getting the api
    type: 'get',
    success: function(data) {

    }
  });
}

function trend10() {
  return $.ajax({
    url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile9").html(), //getting the api
    type: 'get',
    success: function(data) {

    }
  });
}

$.when(trend1(), trend2(), trend3(), trend4(), trend5(), trend6(), trend7(), trend8(), trend9(), trend10()).done(function(trend1_data, trend2_data, trend3_data, trend4_data, trend5_data, trend6_data, trend7_data, trend8_data, trend9_data, trend10_data) {
  //do something                            
})

我如何将这个庞大的代码放入for循环? ajax允许我这样做吗?

更新1:

function trend0()...
function trend1()...
function trend2()...
function trend3()...
....

$.when(trend1(), trend2()).done(function(trend1_data, trend2_data) {
for (var i = 0; i<N; i++) // with N your n* of cycles 
    eval("trend" + i + "()");
}

}

我在做下面的事吗?

解决方案:

                var i = "";
                for (var i=0; i<5; i++) {
                var trend = function(i) {
                    if ( $(".numberOfProfile"+i).length ) {
                        return $.ajax({
                            url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile"+ i).html(), //getting the api
                            type: 'get',
                            success: function(data) {

                            }
                        });
                    }
                    else
                    {
                      return false; 
                    }
                }
                    i++
                }

3 个答案:

答案 0 :(得分:1)

如果api调用始终相同,则可以执行for循环

for (var i = 0; i<N; i++) // with N your n* of cycles 
    trend();
}

如果它们不同,你可以做某事(基于你的代码)

function trend0()...
function trend1()...
function trend2()...
function trend3()...
....

for (var i = 0; i<N; i++) // with N your n* of cycles 
    eval("trend" + i + "()");
}

eval会将字符串详细说明为javascript代码https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval

顺便说一句,做某事并不是真的有效,我建议你找另一种方式

如果你想在页面加载上调用这个函数,你可以这样做:

function trend0()...
function trend1()...
function trend2()...
function trend3()...
....

jQuery(document).ready(function(){
    for (var i = 0; i<N; i++) // with N your n* of cycles 
        eval("trend" + i + "()");
    }
});

或者点击动作?

function trend0()...
function trend1()...
function trend2()...
function trend3()...
....

jQuery(document).ready(function(){
    jQuery('#myButtonId').click(function(e){
        e.preventDefault();
        for (var i = 0; i<N; i++) // with N your n* of cycles 
            eval("trend" + i + "()");
        }
    });
});

这取决于您的应用逻辑

答案 1 :(得分:1)

重要提示:您不应该编写所有功能,因为它们看起来都很相似!将来难以维持

如果你知道现有数组中的配置文件的类数,你应该确实循环它。如果它像上面那样从0到10,你可以这样:

var responses = [];

for (var i=0; i<10; i++) {
responses[i] = $.ajax({
    url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile" + i).html(),
    type: 'get',
    success: function(data) {

    }
}

请注意,实际响应日将在responses[i]['response']中找到,或更有可能responses[i]['responseJSON']

编辑:使用$ .when是一个好主意,但是你似乎有很长时间的ajax调用,因此我无法做出最终决定,因为我不知道最终的应用程序。从上面的例子中可以这样:

var trend = function(profileNo) {
    return $.ajax({
    url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile" + profileNo).html(),
    type: 'get',
    success: function(data) {

    }
}

$.when(trend(0), trend(1), ..., trend(10)).done(function(t1, ..., t10) {
      //handle the results here
})

EDIT2:我真的很惊讶你的新解决方案有效。你试过吗?本着这种精神,我会这样做:

var trend = function(profileNo) {
        return $.ajax({
        url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile" + profileNo).html(),
        type: 'get',
        success: function(data) {
           //You could also use this callback to assign the retrieved to a "global" variable for instance 
        }
    });
}

var i=0;
var responses = [];

while($(".numberOfProfile"+i).length ) {
    responses[i] = trend(i);
    i++;
}

答案 2 :(得分:0)

您的格式似乎已修复,因此您可以执行此类操作。

function trend() {
    var trends = [];
    for(var i=0;i<10;i++)
    {
        var urlX = '/dashboard/getTrend' + '?period=30d' + "&profileId="+$(".numberOfProfile"+i).html(), //getting the api

         $.ajax({
             url: urlX
             type: 'get',
             success: function(data) {
                          trends.push(data);       
                       }
               });
      }
}

$.when(trend()).done(function(trendsData){
     // you have all the trends now
});