Google js API用于创建包含JSON数据的饼图

时间:2016-01-06 04:46:29

标签: php jquery json pie-chart

我使用Google jsapi使用getData.php中的JSON数据创建饼图。但我的代码没有按预期工作。

访问getdata.php

<?php  header('Content-Type: application/json');

$mysqli = new mysqli("localhost", "root", "", "test");

if ($mysqli->connect_errno)
{
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

$query01="SELECT a.ratings,
                 a.name
            FROM programming_languages a";
$res01=mysqli_query($mysqli,$query01);

$rows = array();
//flag is not needed
$flag = true;
$table = array();
$table['cols'] = array(

    // Labels for your chart, these represent the column titles
    // Note that one column is in "string" format and another one is in "number" format as pie chart only 
    // required "numbers" for calculating percentage and string will be used for column title
    array('label' => 'name', 'type' => 'string'),
    array('label' => 'ratings', 'type' => 'number')
);

$rows = array();
while($r = $res01->fetch_array(MYSQLI_ASSOC)) {
    $temp = array();
    // the following line will be used to slice the Pie chart
    $temp[] = array('v' => (string) $r['name']); 

    // Values of each slice
    $temp[] = array('v' => (int) $r['ratings']);
    $rows[] = array('c' => $temp);
}

$table['rows'] = $rows;
$jsonTable = json_encode($table);
echo $jsonTable;
?>

这是jQuery脚本:

google.load('visualization', '1.0', {'packages':['corechart']});   
google.setOnLoadCallback(drawChart);

function drawChart() {
      var jsonData = $.ajax({
          url: "getData.php",
          dataType: "json",
          async: false
          }).responseText;

      var data = new google.visualization.DataTable(jsonData);

      var chart = new google.visualization.PieChart(document.getElementById('chart_div2'));
      chart.draw(data, {width: 500, height: 400});
    }

这是我的php数组:

 [
    {
        "name": "C",
        "ratings": "17"
    },
    {
        "name": "Java",
        "ratings": "16"
    },
    {
        "name": "C++",
        "ratings": "9"
    },
    {
        "name": "Objective-C",
        "ratings": "2"
    }
 ]

0 个答案:

没有答案