Điền dữ liệu bằng mã phía máy chủ

Bạn có thể sử dụng mã phía máy chủ để thu thập dữ liệu để điền vào biểu đồ của mình. Mã phía máy chủ của bạn có thể tải tệp trên máy, truy vấn cơ sở dữ liệu hoặc nhận dữ liệu theo một cách khác. Ví dụ sau đây về PHP minh hoạ dữ liệu biểu đồ đọc từ tệp văn bản trên thiết bị khi có yêu cầu về trang. Bạn có thể sao chép các tệp này vào máy chủ của riêng mình, nếu máy chủ đó hỗ trợ PHP.

Lưu ý: Mẫu này yêu cầu jQuery phiên bản 1.6.2 trở lên.

Sử dụng tệp examplePHP.html

Đây là tệp mà người dùng duyệt qua. Hàm drawChart() gọi hàm ajx() của jQuery để gửi truy vấn đến một URL và nhận lại chuỗi JSON. URL ở đây là của tệp getData.php cục bộ. Dữ liệu được trả về thực sự là một DataTable được xác định trong tệp sampleData.json cục bộ. DataTable này được dùng để điền vào biểu đồ hình tròn, sau đó được hiển thị trên trang.

<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>

Tệp getData.php

Khi nhận được một yêu cầu, tệp này sẽ trả về bản sao của tệp sampleData.json cục bộ.

<?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

?>

Tệp mẫuData.json

Phiên bản JSON của một DataTable nhỏ.

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

Thêm thông tin: