您可以使用伺服器端程式碼取得資料,藉此填入圖表資料。您的伺服器端程式碼可透過其他方式載入本機檔案、查詢資料庫或取得資料。下列 PHP 範例示範如何在系統要求網頁時,從本機文字檔讀取圖表資料。如果檔案支援 PHP,您就可以將這些檔案複製到自己的伺服器。
注意:這個範例需要 jQuery 1.6.2 版或更新版本。
使用 PHP.html 檔案範例
這是使用者要瀏覽的檔案。DrawChart() 函式會呼叫 jQuery ajax() 函式將查詢傳送至網址,並取得 JSON 字串。這裡的網址為本機 getData.php 檔案。傳回的資料實際上是本機 sampleData.json 檔案中定義的 DataTable
。這個 DataTable
用於填入圓餅圖,接著顯示於頁面上。
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "getData.php",
dataType: "json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240});
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
getData.php 檔案
這個檔案收到要求時,會傳回本機 sampleData.json 檔案的副本。
<?php
// This is just an example of reading server side data and sending it to the client.
// It reads a json formatted text file and outputs it.
$string = file_get_contents("sampleData.json");
echo $string;
// Instead you can query your database and parse into JSON etc etc
?>
sampleData.json 檔案
{
"cols": [
{"id":"","label":"Topping","pattern":"","type":"string"},
{"id":"","label":"Slices","pattern":"","type":"number"}
],
"rows": [
{"c":[{"v":"Mushrooms","f":null},{"v":3,"f":null}]},
{"c":[{"v":"Onions","f":null},{"v":1,"f":null}]},
{"c":[{"v":"Olives","f":null},{"v":1,"f":null}]},
{"c":[{"v":"Zucchini","f":null},{"v":1,"f":null}]},
{"c":[{"v":"Pepperoni","f":null},{"v":2,"f":null}]}
]
}
更多資訊: