可以使用服务器端代码获取你的图表数据。服务器端代码可以加载本地文件,查询数据库或者以其他方式获取数据。以下这个php例子展示了当页面被请求时如何从本地的text文件读取图表数据。

exampleUsingPHP.html file


此文件中,drawChart()调用jquery的ajax()函数发送url请求并得到返回的json字符串。url请求的是本地文件getData.php。返回数据实际上是本地文件sampleData.json中定义的一个DataTable。这个DataTable就是用来产生展示在页面上的饼图数据。

<html>
<head>
<!--Load the AJAX API-->
<scripttype="text/javascript"src="https://www.google.com/jsapi"></script>
<scripttype="text/javascript"src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<scripttype="text/javascript">

// Load the Visualization API and the piechart package.
google
.load('visualization','1',{'packages':['corechart']});

// Set a callback to run when the Google Visualization API is loaded.
google
.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-->
<divid="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 file

{
"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}]}
]

}




link:

https://developers.google.com/chart/interactive/docs/reference#dataparam


尝试了一下,成功!!!