如何在highcharts中循环数据

时间:2016-03-04 09:32:26

标签: jquery ajax highcharts

如何将变量eNum循环到Highcharts中的y数据中?

我尝试使用for循环指定i来增加parseFloat中的数据,但图表只显示一组数据。这是为什么?

$(document).ready(function() {
  $.extend({
    getValues: function(url) {
      var result = [];
      $.ajax({
        url: url,
        type: 'get',
        dataType: 'json',
        async: false,
        success: function(data) {
          $.each(data, function(index, element) {
            result.push(element.revenue);
          });
        }
      });
      return result;
    }
  });
  var results = $.getValues("<?php echo base_url('admin_controller/get_data_for_graph') ?>");
  for (var i = 0; i < results.length; i++) {
    var eNum = parseFloat(results[i]);
    $('#container').highcharts({
      chart: {
        plotBackgroundColor: null,
        plotBorderWidth: null,
        plotShadow: false,
        type: 'pie'
      },
      title: {
        text: ''
      },
      tooltip: {
        pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
      },
      plotOptions: {
        pie: {
          allowPointSelect: true,
          cursor: 'pointer',
          dataLabels: {
            enabled: true,
            format: '<b>{point.name}</b>: {point.percentage:.1f} %',
            style: {
              color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
            }
          }
        }
      },
      series: [{
        name: 'Brands',
        colorByPoint: true,
        data: [{
          name: "Deluxe",
          y: eNum,
        }, ]
      }]
    });
  }
});

我只想循环eNum

data: [{
    name: "Deluxe",
    y: eNum,
},]

1 个答案:

答案 0 :(得分:0)

每个系列只需要调用一次 highchart(),而不是每个数据点。

我建议首先在ajax调用中使用 parseFloat()将数据转换为数字,如下所示:

    success: function(data) {
      $.each(data, function(index, element) {
        result.push(parseFloat(element.revenue));
      });
    }

然后你不需要for循环,但可以调用 highchart 一次,如下所示:

var results = $.getValues("<?= base_url('admin_controller/get_data_for_graph') ?>");
$('#container').highcharts({
    // ... all the properties you already have, come here...
    // ...
    series: [{
        name: 'Brands',
        colorByPoint: true,
        data: results,
    }]
});

上面没有给出数据点个别名称(标签),因为在你的问题中只有一个这样的标签,它被硬编码为“Deluxe”。

如果你想为每一点提供相同的名称“Deluxe”,那么你可以通过准备结果数组,就像在ajax成功回调中一样:

    success: function(data) {
        $.each(data, function(index, element) {
            result.push({
                name: 'Deluxe', 
                y: parseFloat(element.revenue),
            });
        });
    }

但是,如果您为每个数据点指定了特定的名称,那么这似乎更有用,这可能是PHP可以在Ajax响应中提供的。