サーバー側のコードを使用してデータを取得し、グラフに入力できます。サーバーサイドのコードは、ローカル ファイルの読み込み、データベースに対するクエリの実行、その他の方法でデータの取得を行うことができます。次の PHP の例は、ページがリクエストされたときにローカル テキスト ファイルからグラフデータを読み取る方法を示しています。PHP をサポートしている場合は、独自のサーバーにこれらのファイルをコピーできます。
注: このサンプルには jQuery バージョン 1.6.2 以降が必要です。
exampleUsingPHP.html ファイル
ユーザーが参照するファイルです。drawChart() 関数は jQuery ajax() 関数を呼び出して URL にクエリを送信し、JSON 文字列を返します。ここに示されている URL は、ローカルの getData.php ファイルの URL です。返されるデータは、実際にはローカルの 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}]}
]
}
詳細情報: