将MySQL表值从PHP脚本返回到Javascript函数-实时绘图
我已经搜索了几个小时类似的问题,但没有结果 我使用Highcharts每隔3秒更新一个图表,其中包含特定MySQL表的最后一个条目。我使用示例Javascript代码作为指导。下面是我关心的代码片段将MySQL表值从PHP脚本返回到Javascript函数-实时绘图,javascript,php,mysql,highcharts,livegraph,Javascript,Php,Mysql,Highcharts,Livegraph,我已经搜索了几个小时类似的问题,但没有结果 我使用Highcharts每隔3秒更新一个图表,其中包含特定MySQL表的最后一个条目。我使用示例Javascript代码作为指导。下面是我关心的代码片段 var chart; $('#container').highcharts({ chart: { type: 'spline', animation: Highcharts.svg, // don't animate in old IE marginRight: 10,
var chart;
$('#container').highcharts({
chart: {
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load: function() {
// set up the updating of the chart every 3 seconds
var series = this.series[0];
setInterval(function() {
var x = (new Date()).getTime(), // current time - adjust to align with data vals
y = getyval();
series.addPoint([x, y], true, true);
}, 3000);
…其中函数getyval使用$.get:
我的testget.php文件:
提前谢谢 如果使用justreturn,它将从匿名函数返回,而不是从getyval返回。 第二个问题是getyval是异步的,您在调用之后不会收到值。 您必须提前调用该函数,将其结果保存在某个位置,然后使用它
var yValue = null;
function getyval(){
$.get('testget.php', function(output){
yValue = parseFloat(output);
});
};
像$.get这样的AJAX方法是异步的,这意味着脚本不会等待它们完成。传递给$.get的函数可以返回一些东西,但它有点被转储到位存储桶中,没有任何有用的地方可以返回它
您的代码需要重新设计一点,以充分利用异步的优势。将setInterval内的函数更改为:
现在,当$.get获得其结果并调用其函数时,即PHP运行时,工作就完成了
您可能会担心,异步内容将意味着数据点可能会被无序接收。这不会发生-您正在手动指定x坐标,并且每次运行外部函数时都会创建一个新的x坐标。每个y将与其匹配的x配对
<?php
session_start();
$db = $_SESSION['monitorId'];
$table = $_SESSION['tableId'];
$split_table = explode("_", $table);
$param = $split_table[1];
$dbcon = mysqli_connect("localhost","root","",$db);
$query = "SELECT * FROM ".$table." ORDER BY datetime DESC LIMIT 1";
$lastentry = mysqli_query($dbcon, $query) or die('error reading table');
$row = mysqli_fetch_array($lastentry, MYSQLI_ASSOC);
$yval = $row[$param];
echo $yval;
?>
function getyval(){
$.get('testget.php', function(output){
return parseFloat(output);
});
};
var yValue = null;
function getyval(){
$.get('testget.php', function(output){
yValue = parseFloat(output);
});
};
setInterval(function() {
// current time - adjust to align with data vals
var x = (new Date()).getTime();
// we need to do this in here so `function(result)` can use `x`
$.get('testget.php', function(result) {
// this gets run when the result is received
var y = parseFloat(result);
series.addPoint([x, y], true, true);
});
}, 3000);