【发布时间】:2014-10-16 06:32:04
【问题描述】:
试图让我的 json 输出以正确的格式用于谷歌可视化折线图,但我显然做错了,因为它返回的表没有列。如文档中所述,我使用 Ajax 调用 php 页面。
getData.php
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('water.db');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
//echo "Opened database successfully\n";
}
$sql =<<<EOF
SELECT * from wT;
EOF;
$data = array();
$data['cols'][] = array('label' => 'Temperature', 'type' => 'number');
$data['cols'][] = array('label' => 'Time', 'type' => 'string');
$rows = array();
$ret = $db->query($sql);
while($row = $ret->fetchArray(SQLITE3_ASSOC) ){
$temp = array();
$temp[] = array('v' => (float) $row['fishTemp']);
$temp[] = array('v' => (string) $row['time']);
$rows = array('c' => $temp);
$data['rows'][] = $rows;
}
$jsonTable = json_encode($data, true);
var_dump($jsonTable);
$db->close();
?>
base.html
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.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.
console.log(jsonData);
//var obj = window.JSON.stringify(jsonData);
var data = new google.visualization.DataTable(jsonData);
var options = {
title: 'Title'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
控制台的输出看起来像这样......我错过了什么?!
"{"cols":[{"label":"Temperature","type":"string"},{"label":"Time","type":"date"}],"rows" :[{"c":[{"v":18.25},{"v":"2014-08-19 16:23:23"}]},{"c":[{"v":18.25} ,{"v":"2014-08-19 16:23:31"}]},{"c":[{"v":18.25},{"v":"2014-08-19 16:23 :39"}]},{"c":[{"v":18.25},{"v":"2014-08-19 16:23:47"}]},{"c":[{" v":18.25},{"v":"2014-08-19 16:23:55"}]},{"c":[{"v":18.25},{"v":"2014-08 -19 16:24:06"}]},{"c":[{"v":18.25},{"v":"2014-08-19 16:24:14"}]}
【问题讨论】:
-
缺少
[..]使用json_enode($data, true); -
已更新,但似乎没有用...
-
那么在其他人仅使用您的静态数据运行 google js 代码时可能会出现问题。
-
嘿,再想想
echo $jsonTable;而不是var_dump($jsonTable); -
我感觉这可能与我调用时间戳的方式有关......目前它只是一个字符串,这是不对的。我已经使用 'type' => 'datetime' 验证了,但是当我在 while 循环中调用它时会使用什么?
标签: php ajax json google-visualization