我使用ajax从服务器获取json数据,以动态填充Google条形图的数据。我可能最多从服务器返回20个数据点或0.我在服务器端使用php将数据格式化为json。当我有20个数据点要返回时,代码工作正常,但我想动态建立数据变量,返回的数据点数。我已经尝试了不同的方式来动态填充数组,但无法正常工作。从服务器返回的json数据示例为:
date0: "05/Sep"
date1: "12/Sep"
date2: "17/Apr"
date3: "24/Apr"
date4: "01/May"
date5: "08/May"
date6: "15/May"
date7: "22/May"
rounds_found: 8
score0: "48"
score1: "48"
score2: "45"
score3: "45"
score4: "47"
score5: "49"
score6: "44"
score7: "50"
$("#ajax_image").show(); // Show ajax spinner
$.ajax({
url: 'ajax.php',
dataType: "json",
data: { a: "getBarChart", player_id: $("#player_id").val() },
success: function(data) { //called when successful
$("#ajax_image").hide(); // Hide ajax spinner
// Some raw data (not necessarily accurate)
var data = google.visualization.arrayToDataTable([
['Date','Score' ],
// dynamically add data here
]);
var options = {
title : 'Last 20 Rounds Played',
vAxis: {title: "Scores"},
seriesType: "bars",
series: {1: {type: "line"}}
};
Elements in arrayToDataTable should look like this:
[String(data.date0), parseInt(data.score0)],
[String(data.date1), parseInt(data.score1)],
[String(data.date2), parseInt(data.score2)],
etc.
答案 0 :(得分:4)
对于动态加载,您可以使用以下代码
var bcData = new google.visualization.DataTable();
bcData.addColumn('string', 'Date');
bcData.addColumn('number', 'Score');
for (var i = 0; i < data.rounds_found; i++) {
bcData.addRow([data['date' + i], parseInt(data['score' + i])]);
}
如果没有ajax代码,请参阅example at jsbin。