Highchart不显示图形:错误添加javascript数组

时间:2013-07-18 12:53:43

标签: javascript highcharts

我正在使用高图中的条形图绘制人口信息。我使用Ajax调用获取数据并将它们存储在数组

 $(document).ready(function(){
        var url = 'zone.php';
        var zone_name = [];
        var male_pop = [];
        var female_pop = [];
        $.getJSON(url, function(data) {
            $.each(data, function(index, data) {
                zone_name.push(data.name);
                male_pop.push(parseInt(data.pop_male));
                female_pop.push(parseInt(data.pop_female));
            });
        });

当我使用这些数据绘制图表时,图表不会显示。

$('#chart').highcharts({
            chart: {
                type: 'bar'
            },
            title: {
                text: 'Popolution of Nepal zone wise'
            },
            subtitle: {
                text: 'Source: cbs.gov.np'
            },
            xAxis: {
                categories: zone_name,
                title: {
                    text: null
                }
            },
            yAxis: {
                min: 0,
                title: {
                    text: 'Population',
                    align: 'high'
                },
                labels: {
                    overflow: 'justify'
                }
            },
            tooltip: {
                valueSuffix: ''
            },
            plotOptions: {
                bar: {
                    dataLabels: {
                        enabled: true
                    }
                }
            },
            legend: {
                layout: 'vertical',
                align: 'right',
                verticalAlign: 'top',
                x: -100,
                y: 100,
                floating: true,
                borderWidth: 1,
                backgroundColor: '#FFFFFF',
                shadow: true
            },
            credits: {
                enabled: false
            },
            series: [{
                name: 'Male Population',
                data: male_pop
            }, {
                name: 'Female Population',
                data: female_pop
            }, {
                name: 'Total Population',
                data:  male_pop
            }]
        });
        });

错误发生在series部分。作业data: male_pop不起作用。我怎样才能克服这个错误?

编辑:控制台上的male_pop数组的输​​出是

0: 676960
1: 1122885
2: 990638
3: 1401822
4: 1939350
5: 1500452
6: 706243
7: 1344568
8: 241786
9: 195827
10: 831283
11: 679340
12: 754277
13: 463610

1 个答案:

答案 0 :(得分:3)

我想这个问题是由$.getJSON的asyn性质引起的,当你在此之后调用:$('#chart').highcharts({时,服务器的响应还没有到达。尝试将其更改为:

$.getJSON(url, function(data) {
            $.each(data, function(index, data) {
                zone_name.push(data.name);
                male_pop.push(parseInt(data.pop_male));
                female_pop.push(parseInt(data.pop_female));
            });

        //    $('#chart').highcharts({
        });