Ajax JSON进入Highcharts饼图

时间:2011-07-11 05:13:35

标签: ajax json highcharts

过去几天我遇到过一些问题,他们从外部文件中获取了一些示例json数据,以使用Highcharts库填充饼图。

以下是我在文件中的示例JSON数据:data.json

   [
     ["Apples", 43.0],
     ["Pears", 57.0]
   ]

这是我对highcharts和我的AJAX调用的实现: (我省略了不相关的代码)

<script type="text/javascript">
     $(function() {
       var options = {
            chart: {
                renderTo: 'Chart',
                defaultSeriesType: 'pie'
            },
            title: {
               text:'Fruits'
             },

            plotOptions: {
                 pie: {
                     allowPointSelect: true,
                     cursor: 'pointer',
                     dataLabels: {
                        enabled: true,
                        color: '#000000',
                        connectorColor: '#000000',

                     }
                 }
            },
            series: [{
               type: 'pie',
               name: 'Fruits',
               data: []
            }]
         };

        $.getJSON('data.json', function(json) {

           options.series.push(json);               
           var chart = new Highcharts.Chart(options);
         }).error(function() {console.log('error');});


     });
</script>

基本上,我想将JSON传递给options.series []。data []。继续

options.series.push(json);

我明白了:

[Object, Array[2]] // where the Object contains .name and .type and the Array[2] is my data

我很确定我需要这个:

[Object] // which contains .data , .name, .type

2 个答案:

答案 0 :(得分:5)

我实际上能够通过构造我的JSON来解决我的问题:

[
     {
          "type" : "pie",
          "name" : "Fruits",
          "data" : [
               [
                    "Apple",
                     43.0
               ],
               [  
                    "Pear",
                    "57.0"
               ]
           ]
     }
]

而不是进行数组推送,

我将系列参数设置为JSON,如下所示:

 $.getJSON("data.json", function(json)) {
    options.series = json;
    var chart = new Highcharts.chart(options);
 }

答案 1 :(得分:0)

以防其他人像我一样遇到过这个问题。我用series.data.push解决了同样的问题,因为系列也是一个数组,highcharts不会知道我们实际上是试图将值推送到数据中。