我正在尝试显示这样收集的信息(控制器):
public JsonResult GetDataAssets()
{
List<string[]> data = new List<string[]>();
data.Add(new[] { "Day", "Kasse", "Bonds", "Stocks", "Futures", "Options" });
data.Add(new[] { "01.03.", "200", "500", "100", "0", "10" });
data.Add(new[] { "01.03.", "300", "450", "150", "50", "30" });
data.Add(new[] { "01.03.", "350", "200", "180", "80", "40" });
return Json(data);
}
..在谷歌图表中,像这样(查看):
function drawChart() {
var data = google.visualization.arrayToDataTable($.post('GetDataAssets', {}).responseText);
var options = {
title: 'Performance'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
};
这给了我一个 js 异常,说明数据不是数组。可能没有像我尝试过的那样传递数据。我需要如何处理 ajax 调用返回的数据才能采用有效格式?
回答:
这执行了获取和非常灵活的转换数据,正如上面编写的控制器已经 jsonyfied 一样。很棒的链接:这篇博文
var tdata = new google.visualization.DataTable();
var rows = data.length;
var cols = data[0].length;
tdata.addColumn('string', data[0][0]);
for (var i = 1; i < cols; i++) {
tdata.addColumn('number', data[0][i]);
}
tdata.addRows(data.length);
for (var i = 0; i < data.length; i++) {
tdata.setCell(i, 0, data[i][0]);
for (var j = 1; j < cols; j++) {
var value = parseInt(data[i][j]);
tdata.setCell(i, j, value);
}
}