在getJSON调用中使用highcharts的addChart函数(循环遍历多个本地文件)

时间:2014-01-02 05:29:36

标签: javascript json asynchronous highcharts getjson

我真的被困在这里试图将我的头脑与getjson和javascript循环相结合(这是以前的问题 - How to generate highcharts chart from multiple local json files)。

基本上我正在尝试创建一个包含多个类别和系列的highcharts条形图。我有许多本地json文件,每个文件包含不同信息的计数。我想循环遍历每个类别文件,读取计数并将结果添加到该特定系列(然后绘制它)。我在循环中使用$ .getJSON循环文件(我想我现在通过将它包装在一个函数中来工作(参见下面的代码))。但是,我也试图使用highchart的'chart.addSeries'将每个新系列添加到图表中(即代码中的seriescount)。我目前编码的方式意味着我需要从getJSON调用中返回seriescount - 我知道这不正确,而是应该在getJSON调用中进行进一步处理。这就是我被卡住的部分 - 我不知道如何处理在getJSON调用中添加新系列作为多个系列不断发展的添加的一部分。

我希望上述内容有意义,如果不是,代码本身可能会有所帮助。

(只是补充一点,大部分代码似乎按预期工作 - 这是我无法弄清楚的最后一块)

感谢您的任何建议。

$(document).ready(function() {

  var options = {
  // standard highcharts options set here....
         series: []
  };

  //the series to loop through              
  var fileTypes = new Array('SeriesTypeA', 
                    'SeriesTypeB');

  //the categories to loop through                                      
  var mfiles = new Array('/assets/Cat1.json',
                 '/assets/Cat2.json',
                 '/assets/Cat3.json',
                 '/assets/Cat4.json',
                 '/assets/Cat5.json',
                 '/assets/Cat6.json',
                 '/assets/Cat7.json');

  //plot the initial empty chart              
  var chart = new Highcharts.Chart(options);


  //Loop over the different files and do a count for each
  for (var i=0; i<fileTypes.length; i++) {  
      var seriescount = [];
      for (var j=0; j < mfiles.length; j++) {

          (function(i, j, seriescount){   //force the local i and j
              $.getJSON(mfiles[j], function(data) {
                  // get the count of files
                  var count = 0;
                  var index = 0;
                  var entry;
                  for (index = 0; index < data.length; ++index) {
                      entry = data[index];
                      if (entry.file_processing_status == fileTypes[i]) {
                          count ++;
                      }
                  };
                  seriescount.push(count);
                  return seriescount; //This is not correct
              }); 

          })(i, j, seriescount);
      }

      //add the results to make a new series               
      chart.addSeries({                        
          name: fileTypes[i],
          data: seriescount   //as expected I don't get seriescount at this stage
      }, false);            
  };

  //and now redraw the final chart          
  chart.redraw();

});

1 个答案:

答案 0 :(得分:1)

令人不安的是,这就是这一行:$.getJSON(mfiles[j], function(data) { - 这意味着您要为每个系列(fori变量)加载相同的文件。对我来说很奇怪。

现在关于解决方案,每个系列都有固定数量的类别,对吧?它位于mfiles.length变量中。你可以增加一些计数器,并添加它(在你的getJSON回调中):

if(categoryCounter == mfiles.length){ 
  chart.addSeries(series);
}