通过AJAX将数组传递给Google Charts API

时间:2012-03-22 19:29:33

标签: javascript php ajax google-visualization

我可以使用以下方式获取注册特定日期的用户数量:

$query = "SELECT COUNT(*), DATE(FROM_UNIXTIME(time)) as date
   FROM user GROUP BY DATE(FROM_UNIXTIME(time))";

Google Charts提供以下用于绘制图表的JS函数

function drawChart() {
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Day');
    data.addColumn('number', 'Users');
    data.addRows([
      ['03-22-2012', 1000],
      ['03-23-2011', 1170]
    ]);

    var options = {
      title: 'Signups'
    };

    var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
    chart.draw(data, options);
  }

如何通过data.addRowsajax一起使用我的数据库查询?我被困在这里..非常感谢!

由于

1 个答案:

答案 0 :(得分:0)

通过使用一行stackoverflowtest_(时间戳)来模仿上面描述的内容,解决了这个问题:

time_
-------------------
2013-07-07 13:23:31
2013-07-07 13:23:44
2013-07-09 13:23:50
2013-07-08 13:23:57
2013-07-09 13:24:07
2013-07-09 13:24:14

googlechart.php,哪个输出将通过AJAX获取:

<?
mysql_connect('localhost','root','xxx');
mysql_select_db('test');

$SQL='SELECT COUNT(*) as c, DATE(time_) as date FROM stackoverflow GROUP BY DATE(time_)';
$result=mysql_query($SQL);

$a = array();
$a['cols'][] = array('type' => 'string', 'label' => 'Day');
$a['cols'][] = array('type' => 'number', 'label' => 'Users');
while($row = mysql_fetch_assoc($result)) {
    $a['rows'][]['c']=array(
        array('v' => $row['date']),
        array('v' => $row['c'])
    );
}
echo json_encode($a);
?>

googlechart.html(实际页面)使用jQuery AJAX并生成如上所述的谷歌图表:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">google.load('visualization', '1.0', {'packages':['corechart']});</script>
<script type="text/javascript">
function drawChart(json) {
   var data = new google.visualization.DataTable(json);
   var options = {
      title: 'Signups'
   };
   var chart = new  google.visualization.LineChart(document.getElementById('chart_div'));
      chart.draw(data, options);
   }
   $(document).ready(function() {
      $.ajax({
        url: 'googlechart.php',
        success : function(json) {
            drawChart(json);
        }
     });
   });
</script>

<div id="chart_div" style="width:500px;height:400px;"></div>

结果

enter image description here