由於andyg1和上升,我能夠做出像這樣的工作(使用PrototypeJS而不是jQuery的,但這個想法是一樣的)。由於這一點並不明顯,我將展示所有步驟。
Ajax端點剛剛返回json,看起來像這樣(一個.NET MVC模板)。請注意,我發現我已經引述一切這Google's documentation並不表明是必要的:
<%
Response.Headers.Add("Content-type", "text/json");
Response.AddHeader("Content-type", "application/json");
%>
{
"cols": [
{"id": "col_1", "label": "Date", "type": "string"},
{"id": "col_2", "label": "Score", "type": "number"}
],
"rows": [
<%
int index = 0;
foreach(KeyValuePair<string, double> item in Model.Performance) { %>
{"c":[{"v":"<%= item.Key %>"}, {"v":<%= item.Value %>}]}<%= (index == Model.Performance.Count - 1) ? "" : "," %>
<% index++; %>
<%
}
%>
]
}
然後母版頁包含在此:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="/js/myJavascriptFile.js" />
然後在myJavascriptFile.js(注意的最後一行初始化方法是google.setOnLoadCallback這在我的課沒有drawChart)調用的方法:
google.load('visualization', '1', {'packages':['corechart']});
var colors = {'blue': '#369', 'red': '#c22', 'green': '#283', 'yellow': '#c91'};
var MyClass = Class.create({
initialize: function() {
...
google.setOnLoadCallback(this.getTeamCharts);
},
getTeamCharts: function() {
$$(".chart-wrapper").each(function (div) {
var chartData = div.getData();
var parameters = {
...
};
new Ajax.Request('/endpoints/TeamChart.aspx', {
method: 'get',
parameters: parameters,
onSuccess: function(transport) {
var jsonData = transport.responseJSON;
var data = new google.visualization.DataTable(jsonData);
var chartColor = colors[parameters.TeamColor];
var chartDivId = 'chart_div_' + parameters.TeamIdAsString;
// Set chart options
var options = {
'chartArea': {'left':'15%','top':'15%','width':'80%','height':'70%'},
'legend': {'position': 'none'},
'lineWidth': 3,
'width': 262,
'height': 180,
'colors': [chartColor]
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.LineChart(document.getElementById(chartDivId));
chart.draw(data, options);
}
});
});
}
});
document.observe("dom:loaded", function() {
var thing = new MyClass();
});
我敢肯定,這可以進一步改進,但它的工程!
我正在撕裂我的耳朵,試圖弄清楚這一點,但讀到你的評論,它突然變得有意義。在示例代碼中,在「google.load ...」語句之後,總有一條語句,如google.setOnLoadCallback(drawVisualization);但是當然你不需要使用回調函數,你可以在你準備好繪製它時自己調用drawVisualization()方法。 – Ascendant
你不知道這個答案的結構和幫助有多好!很容易被忽視,因爲你沒有將問題標記爲答案(即使你提供了自己的答案,也請做),但是非常有幫助! – SW4
我的壞!只是標記了它。 – andyg1