我正在尝试为' sale v / s return'创建图表。在我的项目中。我正在使用带有Java的谷歌API和来自数据库的数据。我的代码如下,
JS代码:
google.charts.load('current', {packages: ['corechart', 'line']});
google.charts.setOnLoadCallback(drawTrendlines);
function drawTrendlines() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'X');
data.addColumn('number', 'Sale');
data.addColumn('number', 'Return');
var bb="BPS40L 1 Y";
var jsonData = $.ajax({
url: "chart?icd="+bb+"&opt="+1,
type: "post",
dataType: "json",
async: false
}).responseText;
var data = google.visualization.arrayToDataTable(jsonData);
var options = {
hAxis: {
title: "day"
},
vAxis: {
title: "Sales"
},
colors: ['#AB0D06', '#007329'],
trendlines: {
0: {type: 'exponential', color: '#333', opacity: 1},
1: {type: 'linear', color: '#111', opacity: .3}
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options, {width: 600, height: 540});
}
});
Java代码:
ArrayList mn1 = new ArrayList();
while (rs.next()) {
JSONObject aListcounter = new JSONObject();
aListcounter.put(i,i);
aListcounter.put("sale",rs.getInt("SLQ"));
aListcounter.put("return",rs.getInt("RTQ"));
mn1.add(aListcounter);
i+=3;
}
rs.close();
ps.close();
response.setContentType("application/json");
//new Gson().toJson(list2, response.getWriter());
JSONObject jObj = new JSONObject();
jObj.put("data",mn1);
out.println(mn1);
我从服务器获取输出如下:
[{"0":0,"sale":"3","return":"13"},{"1":1,"sale":"23","return":"23"}]
没有生成图表。收到错误消息:" not an array
"
答案 0 :(得分:1)
您需要更改服务器发送的数据,使其具有以下格式:
[
["X", "Sale", "Return"],
[0, 3, 13],
[1, 23, 23]
]
google.charts.load('current', {
packages: ['corechart']
});
google.charts.setOnLoadCallback(drawTrendlines);
function drawTrendlines() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'X');
data.addColumn('number', 'Sale');
data.addColumn('number', 'Return');
var bb = "BPS40L 1 Y";
var jsonData =
[
["X", "Sale", "Return"],
[0, 3, 13],
[1, 23, 23]
];
var data = google.visualization.arrayToDataTable(jsonData);
var options = {
hAxis: {
title: "day"
},
vAxis: {
title: "Sales"
},
colors: ['#AB0D06', '#007329'],
trendlines: {
0: {
type: 'exponential',
color: '#333',
opacity: 1
},
1: {
type: 'linear',
color: '#111',
opacity: .3
}
}
};
var chart =
new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options, {
width: 600,
height: 540
});
}

<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
&#13;