Javascript从外部json读取HighCharts图表数据

时间:2016-06-10 11:14:24

标签: javascript json highcharts

目前我正在阅读包含实际页面内所有数据的HighCharts Chart数据。

以下是完整代码:

<!DOCTYPE html>
<html><head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/highcharts-more.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="http://highcharts.github.io/export-csv/export-csv.js"></script>
<script type="text/javascript">
        parent.$('iframe').height('256');
    </script>

<style>
  .highcharts-tooltip h3 {
    margin: 0.3em 0;
}
</style>

<script>


$(function () {

    $('#container').highcharts({
        chart: {
            type: 'column',
            height: 220
        },
        title: {
            text: ''
        },
        xAxis: {
            categories: ['Data 1', 'Data 2', 'Data 3', 'Data 4', 'Data 5']
        },
        yAxis: {
            min: 0,
            title: {
                text: 'Data by Name'
            },
            stackLabels: {
                enabled: true,
                style: {
                    fontWeight: 'bold',
                    color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
                }
            }
        },
        legend: {
            align: 'right',
            x: -30,
            verticalAlign: 'top',
            y: 25,
            floating: true,
            backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || 'white',
            borderColor: '#CCC',
            borderWidth: 1,
            shadow: false
        },
        tooltip: {
            headerFormat: '<b>{point.x}</b><br/>',
            pointFormat: '{series.name}: {point.y}<br/>Total: {point.stackTotal}'
        },
        plotOptions: {
            column: {
                stacking: 'normal',
                dataLabels: {
                    enabled: true,
                    color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white',
                    style: {
                        textShadow: '0 0 3px black'
                    }
                }
            }
        },
        series: [{
            name: 'Name 3',
            data: [5, 3, 4, 7, 2]
        }, {
            name: 'Name 2',
            data: [2, 2, 3, 2, 1]
        }, {
            name: 'Name 1',
            data: [3, 4, 4, 2, 5]
        }]
    });

});

</script>
  </head>
  <body style="overflow:hidden">


<div id="container" style="height: 400px; margin: 0 auto"></div>


</body></html>

我的问题是,如何修改代码以便从外部json文件中读取数据?

1 个答案:

答案 0 :(得分:2)

以下是fiddle

的示例

另见This answer

$.getJSON('your_json_file.json', function(data) { 
    options.series=data; 
     chart = new Highcharts.Chart(options);            

});