【发布时间】:2017-05-16 08:38:17
【问题描述】:
我正在学习 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 数据而不是按钮单击功能,我可以确保 JSON 数据的格式正确,因为图表正在绘制。
【问题讨论】:
-
如果你对数据进行硬编码并且它可以工作,然后它不能与 json 一起工作,那么它必须是 json 的东西 - 确保你的 json 数据数组是一个数字数组 - 而不是一个数组字符串
-
看不到返回的 JSON 的输出,很难说...
-
这里是 json 数据:[{"name":"city","data":["Multiple Cities","IrvineDallas","Seattle","Irvine","Brazil", "新泽西","莫斯科","亚特兰大","约翰内斯堡","达拉斯","巴尔的摩","印度","锡拉考斯","纽约","阿根廷","迈阿密","芝加哥", "USA","Thailand"]},{"name":"Value","data":[12.5,6,3.3,6.3,8.6,4.9,3.8,3.3,4.8,4.8,3.7,14.3,1.8, 5.7,3.8,1.8,4,2.8,3.8]}]
标签: javascript php jquery json highcharts