1

我正在尝试使用 php 从 mysql 数据生成谷歌图表。到目前为止,这是我的代码:get_json.php

<?php
/* $server = the IP address or network name of the server
 * $userName = the user to log into the database with
 * $password = the database account password
 * $databaseName = the name of the database to pull data from
 * table structure - colum1 is cas: has text/description - column2 is data has the value
 */
$con = mysql_connect('localhost','root','') ;

mysql_select_db('gcm', $con); 

// write your SQL query here (you may use parameters from $_GET or $_POST if you need them)
$query = mysql_query('SELECT count(name) As Subscribers,CAST(`created_at` AS DATE) As Date FROM gcm_users GROUP BY created_at ORDER BY created_at')or die(mysql_error());

$table = array();
$table['cols'] = array(
    /* define your DataTable columns here
     * each column gets its own array
     * syntax of the arrays is:
     * label => column label
     * type => data type of column (string, number, date, datetime, boolean)
     */
    // I assumed your first column is a "string" type
    // and your second column is a "number" type
    // but you can change them if they are not
    array('label' => 'Date', 'type' => 'string'),
    array('label' => 'Subscribers', 'type' => 'number')
);

$rows = array();
while($r = mysql_fetch_assoc($query)) {
    $temp = array();
    // each column needs to have data inserted via the $temp array
    $temp[] = array('v' => $r['Date']);
    $temp[] = array('v' => (int) $r['Subscribers']); 

    // insert the temp array into $rows
    $rows[] = array('c' => $temp);
}

// populate the table with rows of data
$table['rows'] = $rows;

// encode the table as JSON
$jsonTable = json_encode($table);

// set up header; first two prevent IE from caching queries
header('Cache-Control: no-cache, must-revalidate');
header('Content-type: application/json');

// return the JSON data
echo $jsonTable;
?>

它显示正确:{"cols":[{"label":"Date","type":"string"},{"label":"Subscribers","type":"number"}],"rows":[{"c":[{"v":"2013-04-14"},{"v":1}]},{"c":[{"v":"2013-04-15"},{"v":1}]}]} 这是我显示的位置:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>
      Google Visualization API Sample
    </title>
    <script type="text/javascript" src="http://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load('visualization', '1', {packages: ['corechart']});
    </script>
    <script type="text/javascript">
      function drawVisualization() {
        var jsonData = null;

        var json = $.ajax({
          url: "get_json.php", // make this url point to the data file
          dataType: "json",
          async: false,
          success: (
        function(data) {
            jsonData = data;
        })
        }).responseText;



        // Create and populate the data table.
        var data = new google.visualization.DataTable(jsonData);


        // Create and draw the visualization.
      var chart= new google.visualization.LineChart(document.getElementById('visualization')).
            draw(data, {curveType: "function",
                        width: 500, height: 400,
                        vAxis: {maxValue: 10}}
                );
      }


      google.setOnLoadCallback(drawVisualization);
    </script>
  </head>
  <body style="font-family: Arial;border: 0 none;">
    <div id="visualization" style="width: 500px; height: 400px;"></div>
  </body>
</html>

但是当我运行这段代码时,我什么也没得到,它是空白的!我的错误在哪里?

4

1 回答 1

4

现在测试:

您的页面中没有包含 jQuery。将此行添加到您的中<head>,它可以工作。

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

如果您的 AJAX 调用需要更长的时间,可能会发生另一件事:success: function()在 AJAX 调用完成后调用您时,脚本的其余部分已经运行。该脚本不会等到 AJAX 调用完成,直到执行“创建和填充”部分。您必须将这些行放在success: function().

<script type="text/javascript">
  function drawVisualization() {
    var jsonData = null;

    var json = $.ajax({
      url: "get_json.php", // make this url point to the data file
      dataType: "json",
      async: false,
      success: (
    function(data) {
        jsonData = data;

    // Create and populate the data table.
    var data = new google.visualization.DataTable(jsonData);

    // Create and draw the visualization.
  var chart= new google.visualization.LineChart(document.getElementById('visualization')).
        draw(data, {curveType: "function",
                    width: 500, height: 400,
                    vAxis: {maxValue: 10}}
            );

    })
    }).responseText;



  }


  google.setOnLoadCallback(drawVisualization);
</script>

这样,您可以确保所有相关代码仅在 AJAX 调用完成后执行。

于 2013-04-15T13:27:06.757 回答