【发布时间】:2014-08-05 02:17:10
【问题描述】:
我正在尝试使用Chart.js 将 JSON 数据输出到图表,并在 MySQL 数据库中查询数据。
基本上我查询的是(data.php):
<?php
header('Content-Type: application/json');
$con = //Database connection
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to DataBase: " . mysqli_connect_error();
}
else
{
$data_points = array();
$result = mysqli_query($con, "SELECT * FROM condicao order by id desc limit 10");
while($row = mysqli_fetch_array($result))
{
$point = array($row['timestamp'], $row['temperatura']);
array_push($data_points, $point);
}
echo json_encode($data_points, JSON_NUMERIC_CHECK);
}
mysqli_close($con);
?>
这给了我以下数组 (timestamp,temperature):
[
["2014-08-04 23:06:01",16.9],
["2014-08-04 23:03:02",17.1],
["2014-08-04 23:00:02",17.1],
["2014-08-04 22:57:01",17.1],
["2014-08-04 22:54:01",17.1],
["2014-08-04 22:51:02",17.1],
["2014-08-04 22:48:01",17.2],
["2014-08-04 22:45:02",17.2],
["2014-08-04 22:42:01",17.2],
["2014-08-04 22:39:02",17.2]
]
现在我正在尝试将其输出到图表,但我不知道如何将第一个对象作为标签(时间戳),将第二个对象作为数据点(温度)。
这是我试图输出图表的代码:
<script type="text/javascript">
$(document).ready(function() {
$.getJSON("data.php", function (result) {
var tempData = {
labels : result,
datasets : [{
fillColor : "rgba(172,194,132,0.4)",
strokeColor : "#ACC26D",
pointColor : "#fff",
pointStrokeColor : "#9DB86D",
data : result
}]
}
var temp = document.getElementById('compradores').getContext('2d');
new Chart(temp).Line(tempData);
});
});
</script>
如何将结果标识为标签的第一个对象(时间戳),将数组上的第二个对象标识为数据点(温度)?
在我上面做的方式中,我将时间戳和温度都作为标签。
我已经尝试过result[0],尝试为时间戳定义标签并调用result['timestamp']等等,但都没有成功。
谢谢!
【问题讨论】:
标签: javascript php jquery charts