서버 측 코드를 사용하여 데이터 채우기

서버 측 코드를 사용하여 데이터를 얻어 차트를 채울 수 있습니다. 서버 측 코드는 로컬 파일을 로드하거나 데이터베이스를 쿼리하거나 다른 방식으로 데이터를 가져올 수 있습니다. 다음 PHP 예는 페이지 요청 시 로컬 텍스트 파일에서 차트 데이터를 읽는 방법을 보여줍니다. PHP를 지원하는 경우 이 파일을 자체 서버로 복사할 수 있습니다.

참고: 이 샘플에는 jQuery 버전 1.6.2 이상이 필요합니다.

exampleUsingPHP.html 파일

사용자가 둘러보는 파일입니다. drawChart() 함수는 jQuery apache() 함수를 호출하여 URL에 쿼리를 보내고 JSON 문자열을 다시 가져옵니다. 여기서 URL은 로컬 getData.php 파일의 URL입니다. 반환된 데이터는 실제로 로컬 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}]}
      ]
}

추가 정보: