【发布时间】:2011-06-11 02:23:57
【问题描述】:
有没有一种特殊的方式通过 Ajax 调用创建谷歌图表,不同于静态方法?
我生成的 HTML 是正确的,因为它将从普通的 HTML 文件加载,但是当我调用 Ajax 时,图表中的数据没有显示。
我正在使用 google.setOnLoadCallback() 和 google.load('visualization', '1', {packages: ['table']})
【问题讨论】:
有没有一种特殊的方式通过 Ajax 调用创建谷歌图表,不同于静态方法?
我生成的 HTML 是正确的,因为它将从普通的 HTML 文件加载,但是当我调用 Ajax 时,图表中的数据没有显示。
我正在使用 google.setOnLoadCallback() 和 google.load('visualization', '1', {packages: ['table']})
【问题讨论】:
您需要从 ajax 调用中获取数据,然后将其放入您的可视化函数中。 这是我的代码:
google.load('visualization', '1', { packages: ['corechart'] });
google.setOnLoadCallback(OnLoad);
var url = '/Charting/GetData';
function OnLoad() {
$.ajax({
url: url,
dataType: 'json',
success: function (response) {
drawVisualization(response);
}
});
};
function drawVisualization(response) {
var chart = new google.visualization.ColumnChart(
document.getElementById('visualization'));
var data = new google.visualization.DataTable(response);
chart.draw(data);
};
另外我建议你使用这个类来生成正确的 JSON 响应:
public class ChartHelper
{
public ColInfo[] cols { get; set; }
public DataPointSet[] rows { get; set; }
}
public class ColInfo
{
public string id { get; set; }
public string label { get; set; }
public string type { get; set; }
}
public class DataPointSet
{
public DataPoint[] c { get; set; }
}
public class DataPoint
{
public object v { get; set; } // value
public string f { get; set; } // format
}
那么你可以这样使用它:
[ActionName("data")]
public JsonResult Data()
{
Random r = new Random();
var graph = new ChartHelper
{
cols = new ColInfo[] {
new ColInfo { id = "A", label = "Name", type = "string" },
new ColInfo { id = "B", label = "Value", type = "number" },
},
rows = new DataPointSet[] {
new DataPointSet {
c = new DataPoint[]
{
new DataPoint { v = "Name" },
new DataPoint { v = r.NextDouble()},
}},
new DataPointSet {
c = new DataPoint[]
{
new DataPoint { v = "Name2" },
new DataPoint { v = r.NextDouble()},
}},
new DataPointSet {
c = new DataPoint[]
{
new DataPoint { v = "Name3" },
new DataPoint { v = r.NextDouble()},
}}
}
};
return Json(graph, JsonRequestBehavior.AllowGet);
}
【讨论】: