javascript 使用highcharts将动态数据从mysql数据库添加到折线图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30256040/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add dynamic data to line chart from mysql database with highcharts
提问by duong khang
I want to add data point to my line chart with ajax or json, now i must reload whole webpage to show my new data on chart. But i want to show live data by adding point like these link:
我想使用 ajax 或 json 将数据点添加到我的折线图,现在我必须重新加载整个网页才能在图表上显示我的新数据。但我想通过添加像这些链接这样的点来显示实时数据:
www.highcharts.com/studies/live-server.htm
www.highcharts.com/studies/live-server.htm
I was try to retrieve my data from mysql to add on chart by json but nothing happened. This is my code in live-server-data.php :
我试图从 mysql 检索我的数据以通过 json 添加到图表上,但什么也没发生。这是我在 live-server-data.php 中的代码:
<?php
header("Content-type: text/json");
include_once 'include/connection.php';
$db = new DB_Class();
$query = "select distinct idchip from datatable ";
$result = mysql_query( $query );
$rows = array();
$count = 0;
while( $row = mysql_fetch_array( $result ) ) {
$SQL1 = "SELECT datetime,temperature FROM `datatable` WHERE idchip=".$row['0']." datetime DESC limit 0,1 ";
$result1 = mysql_query($SQL1);
while ($rows = mysql_fetch_array($result1)) {
$data[] = $rows['1'];
$datatime[] = 'moment('.$rows['0'].').valueOf()';
}
// The x value is the current JavaScript time, which is the Unix time multiplied
// by 1000.
$x = $datatime;
// The y value is a random number
$y = $data;
}
// Create a PHP array and echo it as JSON
$ret = array($x, $y);
echo json_encode($ret);
?>
and this is what I used to get data and show on chart in my index.php page.
这就是我用来获取数据并在我的 index.php 页面的图表上显示的内容。
var chart; // global
/**
* Request data from the server, add it to the graph and set a timeout to request again
*/
function requestData() {
$.ajax({
url: 'live-server-data.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(eval(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: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'Value',
margin: 80
}
},
series: [{
name: 'Random data',
data: []
}]
});
});
This is my chart which i reload page to get new data right now, but i want to add new point to chart for "real time"
这是我的图表,我现在重新加载页面以获取新数据,但我想“实时”向图表添加新点
回答by Igor
I assume that you have multiple series in graph where backend provides a single point per serie per time.
我假设您在图中有多个系列,其中后端每次为每个系列提供一个点。
For the sake of simplicity I suggest you returning time in milliseconds. I'm not too strong in PHP but I guess the point is clear
为简单起见,我建议您以毫秒为单位返回时间。我在 PHP 方面不太强,但我想这点很清楚
<?php
header("Content-type: text/json");
include_once 'include/connection.php';
$db = new DB_Class();
$query = "select distinct idchip from datatable ";
$result = mysql_query( $query );
$rows = array();
$count = 0;
while( $row = mysql_fetch_array( $result ) ) {
$SQL1 = "SELECT datetime,temperature FROM `datatable` WHERE idchip=".$row['0']." ORDER BY datetime DESC limit 0,1 ";
$serie = new StdClass;
$serie->name = $row['0'];
$result1 = mysql_query($SQL1);
$points = array();
while ($rows = mysql_fetch_array($result1)) {
$points[] = array(strtotime($rows['0']) * 1000, $rows['1']);
}
$serie->data = $points;
$series[] = $serie;
}
// Create a PHP array and echo it as JSON
$ret = $series;
echo json_encode($ret);
?>
Client-side code will be:
客户端代码将是:
var chart;
var chartSeries = {};
var latestTimeReported = {};
function requestData() {
$.ajax({
url: 'live-server-data.php',
success: function(seriesUpdate) {
//in case initializer of highcharts is too quick - skip the update
if (!chart) {
setTimeout(requestData, 1000);
return;
}
$.each(seriesUpdate, function (serieIndex, serieUpdate) {
var existingSerie = chartSeries[serieUpdate.name];
var newPoint = serieUpdate.data[0];
var lastInsertedTime = latestTimeReported[serieUpdate.name];
if (lastInsertedTime && lastInsertedTime < newPoint[0]) {
console.log('Attempt inserting old data!!!!');
return;
}
latestTimeReported[serieUpdate.name] = newPoint[0];
if (existingSerie) {
var shift = existingSerie.data.length > 20;
existingSerie.addPoint(newPoint , true, shift);
} else {
var newSerie = chart.addSeries({
name: serieUpdate.name,
data: serieUpdate.data
}, true);
chartSeries[serieUpdate.name] = newSerie;
}
});
// 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: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'Value',
margin: 80
}
},
series: []
});
You can see new updated example here http://plnkr.co/edit/OqMofEGDadF9J3Uit8qD
您可以在此处查看新的更新示例 http://plnkr.co/edit/OqMofEGDadF9J3Uit8qD
回答by Wacharapon Jantasang
show "Attempt inserting old data!!!!". and No Show Display data Real-time.
显示“尝试插入旧数据!!!!”。和 No Show 实时显示数据。
Display
展示
JSON
JSON