您可以使用服务器端代码来获取数据来填充图表。您的服务器端代码可以加载本地文件、查询数据库或以其他方式获取数据。以下 PHP 示例演示了在请求页面时从本地文本文件中读取图表数据。您可以将这些文件复制到自己的服务器(如果服务器支持 PHP)。
注意:此示例需要使用 jQuery 1.6.2 或更高版本。
exampleUsingPHP.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}]}
]
}
更多信息: