解決google chart使用服務器端代碼獲取填充數據--json格式

可以使用服務器端代碼獲取你的圖表數據。服務器端代碼可以加載本地文件,查詢數據庫或者以其他方式獲取數據。以下這個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


嘗試了一下,成功!!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章