Highcharts setData无法使用php,json点击按钮

时间:2017-05-16 08:38:18

标签: javascript php jquery json highcharts

我正在学习高级图表,并且陷入了使用php,json的新数据更新图表的情况。我已经通过创建一个包含数据的单独图表来验证新数据是否采用正确的JSON格式。

以下是我的代码:

var my_chart;

    var options = {
    chart: {
        renderTo: 'container',
        type: 'column',
        marginRight: 130,
        marginBottom: 75,
    },
    title: {
        text: 'Man Weeks Allocation Region Wise',
        x: -20 //center
    },
     plotOptions: {
            column: {
                dataLabels: {
                    enabled: true
                },
                enableMouseTracking: false
            }
        },
    subtitle: {
        text: 'True that',
        x: -20
    },
    xAxis: {
        categories: []
    },
    yAxis: {
        title: {
            text: 'Count'
        },
        gridLineColor: '#197F07',
        gridLineWidth: 0,
        lineWidth:1,
        plotLines: [{
            value: 0,
            width: 1,
            color: '#808080'
        }]
    },
    tooltip: {
        formatter: function() {
        return '<b>'+ this.series.name +'</b><br/>'+
        this.x +': '+ this.y;
        }
    },
    legend: {
        layout: 'vertical',
        align: 'right',
        verticalAlign: 'top',
        x: -10,
        y: 100,
        borderWidth: 0
    },
    credits: {
        enabled: false
      },

    series: []
    }


 $(document).ready(function() {
    $.getJSON("getData.php", function(json) {
        console.log(json[0]);
        console.log(json[1]);
    options.xAxis.categories = json[0]['data'];
    options.series[0] = json[1];
    my_chart = new Highcharts.Chart(options);
    });
 });


$("#button1" ).click(function() {
    $.getJSON("getNewData.php", function(data) {
        console.log(data[0]);
        console.log(data[1]);       
        my_chart.series[0].setData(data[1]);
        my_chart.xAxis[0].setCategories(data[0]['data']);
    });
});

当我点击按钮时,它会在控制台上打印正确的数据,但图表没有更新,之前的图表数据也消失了。

但如果我对数据进行硬编码,则以下情况有效:

$("#button1" ).click(function() {
    $.getJSON("getNewData.php", function(data) {
        console.log(data[0]);
        console.log(data[1]);   
        my_chart.series[0].setData([1,2,3,4,5]);
        my_chart.xAxis[0].setCategories(['A','B','C','D','E']);
    });
});

我是否缺少动态更改数据的内容?

我可以确保JSON数据的格式正确,因为如果我在文档就绪函数中使用相同而不是按钮单击功能,则图表正在绘制。

1 个答案:

答案 0 :(得分:0)

在选项中设置xAxis.categories和系列并再次创建图表工作正常。

$("#city" ).click(function() {
    $.getJSON("getNewData.php", function(data) {
        console.log(data[0]);
        console.log(data[1]);
        options.xAxis.categories = data[0]['data'];
        options.series[0] = data[1];
        my_chart = new Highcharts.Chart(options);
    });
});

有没有其他方法可以使用setData和setCategories更新图表?