Table 没有专栏 - Google 图表 - PHP AJAX

Table has no columns - Google Charts - PHP AJAX

我今天开始学习如何使用 Google 图表,我有点卡住了。

我有动态数据(每天大约变化 3-4 次)要输入到图表(饼图)中。我使用 AJAX 作为数据源,PHP 作为我的后端。我尝试这样做但无济于事:

AJAX:

<?php
include $_SERVER['DOCUMENT_ROOT'].'/includes/galaxy-connect.php';

$database = new Connection();
$database = $database->Connect();
$statement = $database->Prepare(" SELECT COUNT(Membership_Level_Name) AS MemTotal, Membership_Level_Name
FROM membership AS M
LEFT JOIN membership_levels AS L
ON M.`Membership_Level_Id` = L.`Membership_Level_Id`
LEFT JOIN membership_status AS S
ON M.`MembershipStatusId` = S.MembershipStatusId
WHERE M.`MembershipStatusId` = 1
GROUP BY L.`Membership_Level_Name`
ORDER BY L.`Membership_Level_Id` ");

$statement->execute();
$MembershipTotals = $statement->fetchall(PDO::FETCH_ASSOC); 

if (!empty($MembershipTotals)) {
    foreach ($MembershipTotals as $MembershipTotal) {
        $data[] = array(
            "cols" => array("id"=>"Membership_Level_Name", "label"=>"Membership Level", "type"=>"varchar"),
                 array("id"=>"MemTotal", "label"=>"Total", "pattern"=>"", "type"=>"number"),
            "rows" => array($MembershipTotal['Membership_Level_Name'], $MembershipTotal['MemTotal'])
        );
    }
}

echo json_encode($data);

这就是我的 ajax,它产生:

(好的,我不会 post 图片,但这是结果)

[{"cols":{"id":"Membership_Level_Name","label":"Membership Level","type":"varchar"},"0":{"id":"MemTotal","label":"Total","pattern":"","type":"number"},"rows":["Start Up","24"]},{"cols":{"id":"Membership_Level_Name","label":"Membership Level","type":"varchar"},"0":{"id":"MemTotal","label":"Total","pattern":"","type":"number"},"rows":["Member","131"]},{"cols":{"id":"Membership_Level_Name","label":"Membership Level","type":"varchar"},"0":{"id":"MemTotal","label":"Total","pattern":"","type":"number"},"rows":["Member Plus","170"]},{"cols":{"id":"Membership_Level_Name","label":"Membership Level","type":"varchar"},"0":{"id":"MemTotal","label":"Total","pattern":"","type":"number"},"rows":["Premier Member","31"]},{"cols":{"id":"Membership_Level_Name","label":"Membership Level","type":"varchar"},"0":{"id":"MemTotal","label":"Total","pattern":"","type":"number"},"rows":["Bronze","97"]},{"cols":{"id":"Membership_Level_Name","label":"Membership Level","type":"varchar"},"0":{"id":"MemTotal","label":"Total","pattern":"","type":"number"},"rows":["Silver","145"]},{"cols":{"id":"Membership_Level_Name","label":"Membership Level","type":"varchar"},"0":{"id":"MemTotal","label":"Total","pattern":"","type":"number"},"rows":["Gold","188"]},{"cols":{"id":"Membership_Level_Name","label":"Membership Level","type":"varchar"},"0":{"id":"MemTotal","label":"Total","pattern":"","type":"number"},"rows":["Affiliate","3"]},{"cols":{"id":"Membership_Level_Name","label":"Membership Level","type":"varchar"},"0":{"id":"MemTotal","label":"Total","pattern":"","type":"number"},"rows":["Charity\/Education","4"]}]

所以下一步是调用该数据,我从 Google 图表 "Connecting to a database"(或类似的东西)页面获取了代码:

  <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">

    // Load the Visualization API and the piechart package.
    google.load('visualization', '1', {'packages':['corechart']});

    // Set a callback to run when the Google Visualization API is loaded.
    google.setOnLoadCallback(drawChart);

    function drawChart() {
      var jsonData = $.ajax({
          url: "/ajax/charts/membershiptotals.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>

重新加载网页并产生错误:

Table 没有列

我不明白为什么……我查看了其他解决方案,并在 Quora 和 Google 小组上 API 进行了 post 编辑,但无济于事。有人告诉我代码有什么问题吗??

这是要传递的数组格式。

javascript:

var jsondata; //json data recived from php script
var data = google.visualization.arrayToDataTable(jsondata);

php:

$data = array(
    array('Membership Level', 'MemTotal'),
      array('Member Plus', 170),
      array('Member', 131)
    );
echo json_encode($data);

你必须传递 Json 数组而不是对象。

我找到了答案:

AJAX 更改为:

<?php

    include $_SERVER['DOCUMENT_ROOT'].'/includes/galaxy-connect.php';

    $database = new Connection();
    $database = $database->Connect();
    $statement = $database->Prepare(" SELECT COUNT(Membership_Level_Name) AS MemTotal, Membership_Level_Name
                FROM membership AS M
                LEFT JOIN membership_levels AS L
                                ON M.`Membership_Level_Id` = L.`Membership_Level_Id`
                LEFT JOIN membership_status AS S
                                                                                                                        ON M.`MembershipStatusId` = S.MembershipStatusId
                                                                                                                        WHERE M.`MembershipStatusId` = 1
                                GROUP BY L.`Membership_Level_Name`
        ORDER BY L.`Membership_Level_Id` ");
    $statement->execute();
    $MembershipTotals = $statement->fetchall(PDO::FETCH_OBJ);   


    $col1=array();
    $col1["id"]="";
    $col1["label"]="Membership Type";
    $col1["pattern"]="";
    $col1["type"]="string";

    $col2=array();
    $col2["id"]="";
    $col2["label"]="Total";
    $col2["pattern"]="";
    $col2["type"]="number";

    $cols = array($col1,$col2);

    $rows=array();

        foreach ($MembershipTotals AS $MembershipTotal) {  //foreach ($Event->TrainingTotals['ConfirmedTotal'] AS $Key => $Value) {
            $cell0["v"]=$MembershipTotal->Membership_Level_Name;
            $cell1["v"]=intval($MembershipTotal->MemTotal);

        $row0["c"]=array($cell0,$cell1);
        array_push($rows, $row0);
        }

    $data=array("cols"=>$cols,"rows"=>$rows);
    echo json_encode($data);

这使它变得更容易一些,然后在实际页面上:

<script type="text/javascript">
    // Load the Visualization API and the piechart package.
    google.load('visualization', '1', {'packages':['corechart']});

    // Set a callback to run when the Google Visualization API is loaded.
    google.setOnLoadCallback(drawChart);
    function drawChart() {
        var jsonData = $.ajax({
            url: "/ajax/charts/membershiptotals.php",
            dataType:"json",
            async: false
        }).responseText;

    // Create our data table out of JSON data loaded from server.
    var data = new google.visualization.DataTable(jsonData);
    var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
        chart.draw(data, {title:'Membership Bookings', width: 800, height: 500});
    }


</script>

基本上我必须清楚地声明列,并且 intval 是将它变成一个整数,否则它 returns 数字作为一个字符串 Google 不喜欢..希望这对任何人都有帮助:)

感谢 Harish 的回答,但我需要它更有活力:-)