การป้อนข้อมูลโดยใช้โค้ดฝั่งเซิร์ฟเวอร์

คุณใช้โค้ดฝั่งเซิร์ฟเวอร์ในการรับข้อมูลเพื่อสร้างแผนภูมิได้ โค้ดฝั่งเซิร์ฟเวอร์สามารถโหลดไฟล์ในเครื่อง ค้นหาฐานข้อมูล หรือรับข้อมูลด้วยวิธีอื่นได้ ตัวอย่าง PHP ต่อไปนี้สาธิตการอ่านข้อมูลแผนภูมิจากไฟล์ข้อความในเครื่องเมื่อมีการขอหน้าเว็บ คุณสามารถคัดลอกไฟล์เหล่านี้ไปยังเซิร์ฟเวอร์ของคุณเอง หากไฟล์รองรับ PHP

หมายเหตุ: ตัวอย่างนี้ต้องใช้ jQuery เวอร์ชัน 1.6.2 ขึ้นไป

ตัวอย่างการใช้ไฟล์ PHP.html

ซึ่งเป็นไฟล์ที่ผู้ใช้เรียกดู ฟังก์ชันDrawChart() จะเรียกฟังก์ชัน jQuery ajax() เพื่อส่งข้อความค้นหาไปยัง URL และรับสตริง JSON กลับมา URL ตรงนี้เป็นไฟล์ getData.php ในเครื่อง ข้อมูลที่ส่งกลับมาคือ DataTable ที่กําหนดไว้ในไฟล์ sampleData.json ในเครื่อง 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

เวอร์ชัน JSON ของ DataTable ขนาดเล็ก

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

ข้อมูลเพิ่มเติม