我尝试制作样条高图并实施如何将数据从 JSON 加载到高图?,这是米娜加布里埃尔的回答。代码看起来像这样。
在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 代码,它工作正常。我错过了什么?