我嘗試製作樣條高圖並實施How to load data from JSON to Highchart?的解決方案,這是來自Mina Gabriel的答案。代碼看起來像這樣。來自數據庫的動態樣條高圖
在test.php
}
// Set the JSON header
header("Content-type: text/json");
// The x value is the current JavaScript time, which is the Unix time multiplied by 1000.
$x = time() * 1000;
$y = rand(0,100) ;
// Create a PHP array and echo it as JSON
$ret = array($x, $y);
echo json_encode($ret);
?>
而在highchart腳本:
<script>
/**
* Request data from the server, add it to the graph and set a timeout to request again
*/
var chart; // global
function requestData() {
$.ajax({
url: 'http://localhost:8080/test.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20; // shift if the series is longer than 20
// add the point
chart.series[0].addPoint(point, true, shift);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false
});
}
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 100,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'Value',
margin: 80
}
},
series: [{
name: 'Random data',
data: []
}]
});
});
</script>
< /head>
<body>
而那些剛剛工作。但是,當我試圖改變在test.php
的代碼來設置y值從數據庫這樣一個數字:
<?php
header("Content-type: text/json");
$db = mysql_connect("localhost","myusername","mypassword");
mysql_select_db("mydatabase");
$day=date('Y-m-d'); //UTC standar time
$result = mysql_query("SELECT COUNT(*) FROM table WHERE time='{$day}';");
$count = mysql_fetch_array($result);
// The x value is the current JavaScript time, which is the Unix time multiplied by 1000.
$x = time() * 1000;
$y = $count[0];
// Create a PHP array and echo it as JSON
$ret = array($x, $y);
echo json_encode($ret);
?>
線圖不起作用。我檢查了SQL代碼,它的工作原理正確。我錯過了什麼?
你可以請求ajax調用後返回的JSON後? – 2012-08-04 05:27:43
是的,這裏需要更多信息。你可以在ajax成功回調中添加一個斷點「var series = chart.series [0]」,並分享你有的點的確切值 – 2012-08-04 05:47:35
如果有任何答案有幫助,請相應地投票/標記 – 2012-08-06 21:31:05