使用服务器端代码填充数据

您可以使用服务器端代码来获取数据以填充图表。您的服务器端代码可以加载本地文件、查询数据库或以其他方式获取数据。以下 PHP 示例演示了如何在请求页面时从本地文本文件中读取图表数据。您可以将这些文件复制到自己的服务器(如果支持 PHP)。

注意:此示例需要使用 jQuery 版本 1.6.2 或更高版本。

exampleUsePHP.html 文件

这是用户浏览到的文件。drawChart() 函数会调用 jQuery bash() 函数,以将查询发送到网址并获取 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}]}
      ]
}

了解详情