我正在尝试使用 Google Charts Api 创建图表。我的数据存储为 json 文件,如图所示。
{
"1":[{"a":0,"d":0}],
"2":[{"a":0,"d":0}],
"3":[{"a":6,"d":62.92}],
"4":[{"a":1.57,"d":75.32}],
"5":[{"a":1.67,"d":66.45}],
"6":[{"a":1.25,"d":76}],
"7":[{"a":1.36,"d":75.08}],
"8":[{"a":1.59,"d":69.27}],
...
}
我正在获取 json 文件,将对象推送到 JavaScript 数组。它工作没有问题。我添加这些行是为了了解发生了什么。但是 Google Api 不接受我的值,只显示
dots.push([5, 50]);
dots.push([7,60]);
这是我的代码
function drawDots()
{
var data = new google.visualization.DataTable();
data.addColumn('number', 'a');
data.addColumn('number', 'd');
dots = new Array;
dots.push([5, 50]);
dots.push([7,60]);
$.getJSON("/graph/graph.json", function(json)
{
$.each(json, function(id, num)
{
$.each(num, function(i, e)
{
dots.push([e.a, e.d]);
});
});
});
data.addRows(dots);
var options = {
title: '',
hAxis: {title: 'Data 1', minValue: 0, maxValue: 100},
vAxis: {title: 'Data 2', minValue: 0, maxValue: 100},
legend: 'none'
};
var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
值的数据类型是数字,我也尝试过 eval() 。在控制台中,值似乎在数组中。无法理解出了什么问题。
最佳答案
问题出在异步 getJSON 调用上。 getJSON 调用发生,但当它仍在检索 graph.json 的内容时,其余代码就会执行。这意味着 getJSON 回调在绘制图表后运行。
解决方案:将图表绘制代码移至getJSON回调中:
function drawDots()
{
var data = new google.visualization.DataTable();
data.addColumn('number', 'a');
data.addColumn('number', 'd');
dots = new Array;
dots.push([5, 50]);
dots.push([7,60]);
$.getJSON("/graph/graph.json", function(json)
{
$.each(json, function(id, num)
{
$.each(num, function(i, e)
{
dots.push([e.a, e.d]);
});
});
data.addRows(dots);
var options = {
title: '',
hAxis: {title: 'Data 1', minValue: 0, maxValue: 100},
vAxis: {title: 'Data 2', minValue: 0, maxValue: 100},
legend: 'none'
};
var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
chart.draw(data, options);
});
}
关于javascript - 从 Json 获取 Google 图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40830436/