0
我在我的查看頁面中包含Google圖表,但問題是我總是需要重新加載查看頁面才能顯示Google圖表。當我單擊鏈接並轉到此視圖頁面時,Google圖表從不顯示。Rails:谷歌圖表只在重新加載後才加載
這是因爲我使用Ruby on Rails嗎?
當我進入該頁面時,如何在首次顯示時顯示它。
下面的代碼我認爲,包括谷歌圖表:
<!-- Append content in the head tag in layout view-->
<% content_for :for_head do %>
<title>Analysis</title>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script><!--Load the Google JSAPI library-->
<script type="text/javascript">//<!--Load the Google Visualization and chart libraries-->
// Load the Visualization API library and the piechart library.
google.load('visualization', '1', {'packages':['corechart']});
//Immediately after calling google.load(), your code should call google.setOnLoadCallback(my_handler), a Google JSAPI function that calls your handler as soon as all the libraries are loaded.
//Your handler function should create and define the chart.
google.setOnLoadCallback(drawChart);
// My handler function is called drawChart
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
//First, create a DataTable
var dt = new google.visualization.DataTable();
dt.addColumn('string', 'Book Color'); //the first column is about the color of the book
dt.addColumn('number', 'boooks'); // second column is about the number of the book that has corresponding color
dt.addRows([
['Yellow',3],
['Red',4],
['Blue',8],
['Green',13],
['Purple',2],
['Brown',4],
['Violet',9],
['Orange',10],
['White',7],
['Black',2]
]);
//Set chart options, inlcuding title and dimension
var opt = {
'title': 'How many books do I have?',
'is3D':true
};
//Instantiates a chart and specify which container does this chart will go to
var ch = new google.visualization.PieChart(document.getElementById('chart_div_1')); //Here we instantiate a chart as a PieChart that will go into the container whose id is named chart_div_1
//Using the above chart instance, draw a chart according to the datatable and options we defined earlier
ch.draw(dt, opt);
}
</script>
<% end %>
<!--Div that will hold the pie chart-->
<div id="chart_div_1" style="width:800; height:600"></div>
您好,感謝回答與文件的JS代碼。如何將我的js代碼與加載事件中的文檔包裝在一起,爲什麼這會起作用? – Henry
我在上面的腳本中爲你做了檢查showGraph函數,並在結束window.onload調用它。之所以你不會在第一次顯示是因爲你的DOM沒有準備好,並且你在它之前運行了JS代碼,所以它無法找到「id =」chart_div_1「 – Abdullah
另外我把div頂部 – Abdullah