Highchartjs不会加载

时间:2017-03-07 18:55:51

标签: javascript highcharts

我正在尝试使用JSON文件创建两个图表

HTML:

<div id="chart-0" class="chart-box"></div>
<div id="chart-1" class="chart-box"></div>

JS:

$(function() {

  Highcharts.setOptions({
    chart: {
      plotBackgroundColor: null,
      plotBorderWidth: null,
      plotShadow: false,
      type: 'pie'
    },

    tooltip: {
      pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
    },

    plotOptions: {
      pie: {
        dataLabels: {
          enabled: true,
          format: '<b>{point.name}</b> <br>({point.percentage:.1f} %)'
        }
      }
    }

  });


  $.getJSON('https://api.myjson.com/bins/16jm21', function(data) {

    $.each(data, function(key, val) {

      var options = {
        chart: {
          renderTo: 'chart-' + key
        },
        title: {
          text: val.name
        },
        series: [{
          name: val.series.name,
          innerSize: '60%',
          data: [val.series.data]
        }]
      }
      console.log(val.series.data)

      var chart = new Highcharts.Chart(options);


    });
  });

});

JSON:

[{"name":"Projeto 1","series":{"name":"Status","innerSize":"60%","data":[{"name":"Andamento","y":"60","color":"#DDDF00"},{"name":"Concluído","y":"19.2","color":"#3498DB"},{"name":"Atrasado","y":"10.8"},{"name":"Outro","y":"6.5"},{"name":"Outro 2","y":"3.5"}]}},{"name":"Projeto 2","series":{"name":"Status 2","innerSize":"60%","data":[{"name":"Andamento","y":"60","color":"#DDDF00"},{"name":"Concluído","y":"19.2","color":"#3498DB"},{"name":"Atrasado","y":"10.8"},{"name":"Outro","y":"6.5"},{"name":"Outro 2","y":"3.5"}]}}]

此json文件包含两个图表的数据。在我尝试通过将val.series.data传递到options.series.data来推送数据之前,一切似乎都运行良好。图表加载但是它被打破了,好像它没有正确推送val.series.data,它不会在控制台中引发任何错误。我不知道我做错了什么,但看起来我错过了很简单的东西。

一些帮助将不胜感激。

这是jsfiddle:https://jsfiddle.net/9bor1od3/

1 个答案:

答案 0 :(得分:1)

您的示例代码中存在两个问题。

  1. 设置series.data时,如果它已经是数组,则将其包装在数组中。来自:

    data: [val.series.data]
    

    要:

    data: val.series.data
    
  2. series.data检索到的getJSON会返回y值的字符串。你可以修改来源:

    {"name":"Outro","y":"6.5"}
    

    要:

    {"name":"Outro","y": 6.5}
    

    parseFloat结果。一个parseFloat示例:

    $.each(val.series.data, function(k, v) {
        val.series.data[k].y = parseFloat(val.series.data[k].y);
    });
    
  3. 查看显示的图表的this JSFiddle demonstration