我想创建一个动态的Google折线图,其中填充了JSONArray中的数据。我有以下代码:
<div id="curve_chart" style="margin-bottom: -12px; margin-left: -28px;"></div>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', { 'packages': ['corechart'] });
google.charts.setOnLoadCallback(drawChart0);
function drawChart0() {
var data = new google.visualization.DataTable(JSONArray);
// assumes "day" is a date and "totalfeedings" is a number
data.addColumn('string', 'Day');
data.addColumn('number', 'TotalFeedings');
for (var i = 0; i < JSONArray.length; i++) {
data.addRow([JSONArray[i].Day, JSONArray[i].TotalFeedings]);
}
var options0 = {
curveType: 'function',
legend: 'none',
lineWidth: 6,
width: 440,
height: 180,
backgroundColor: 'transparent',
axisTitlesPosition: 'in',
color: '#286090',
trendlines: {
type: 'linear',
color: 'green',
lineWidth: 3,
opacity: 0.3,
showR2: true,
visibleInLegend: true
},
vAxis: {
gridlines: {
count: 8
}
}
};
var chart0 = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart0.draw(data, options0);
}
</script>
JSONArray包含以下数据:
{
"data": [
{ "Day": "2019-09-13T00:00:00", "TotalFeedings": 3 },
{ "Day": "2019-09-14T00:00:00", "TotalFeedings": 10 },
{ "Day": "2019-09-15T00:00:00", "TotalFeedings": 14 },
{ "Day": "2019-09-16T00:00:00", "TotalFeedings": 19 },
{ "Day": "2019-09-17T00:00:00", "TotalFeedings": 14 },
{ "Day": "2019-09-18T00:00:00", "TotalFeedings": 24 },
{ "Day": "2019-09-19T00:00:00", "TotalFeedings": 15 },
{ "Day": "2019-09-20T00:00:00", "TotalFeedings": 18 },
{ "Day": "2019-09-21T00:00:00", "TotalFeedings": 14 },
{ "Day": "2019-09-22T00:00:00", "TotalFeedings": 10 },
{ "Day": "2019-09-23T00:00:00", "TotalFeedings": 13 },
{ "Day": "2019-09-24T00:00:00", "TotalFeedings": 9 },
{ "Day": "2019-09-25T00:00:00", "TotalFeedings": 11 },
{ "Day": "2019-09-26T00:00:00", "TotalFeedings": 8 },
{ "Day": "2019-09-27T00:00:00", "TotalFeedings": 7 },
{ "Day": "2019-09-28T00:00:00", "TotalFeedings": 2 }
]
}
该图表未出现。
我想知道我在做什么错了。
答案 0 :(得分:0)
像下面一样创建一个数组
您需要执行JSONArray.data[i].Day
和JSONArray.data[i].TotalFeedings
才能访问JSON数据。
JSONArray = {
"data": [
{
"Day": "2019-09-13T00:00:00",
"TotalFeedings": 3
},
{
"Day": "2019-09-14T00:00:00",
"TotalFeedings": 10
},
{
"Day": "2019-09-15T00:00:00",
"TotalFeedings": 14
}
//rest of your data
]
}
// change from this
data.addRow([JSONArray[i].Day, JSONArray[i].TotalFeedings]);
// to this
data.addRow([JSONArray.data[i].Day, JSONArray.data[i].TotalFeedings]);