是否有通过Ajax调用创建Google图表的特殊方法,这与静态方法不同?
我正在生成的HTML是正确的,因为它将从普通的HTML文件加载,但是当我调用Ajax时,图表中的数据没有显示。
我正在使用google.setOnLoadCallback()和google.load('visual','1',{packages:['table']})
答案 0 :(得分:0)
您需要从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);
}