Highcharts setData在按钮单击时无法使用php,json



我正在学习高图表,并陷入了使用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 数据的格式是正确的,因为图表正在绘制。

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

$("#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 和 setCategory 更新图表?

最新更新