使用伺服器端程式碼填入資料

你可以使用伺服器端程式碼來取得資料以填入圖表。您的伺服器端程式碼可以載入本機檔案、查詢資料庫,或透過其他方式取得資料。以下 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 檔案

小型 DataTable 的 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}]}
      ]
}

其他資訊: