我已经使用以下Highchart的演示创建了Highchart:
https://www.highcharts.com/demo/dynamic-update
现在,我创建了自己的函数以向图表添加动态值。
我创建了一个函数来从特定的php文件中获取动态数据,该文件的数据在每次页面加载事件中都会发生变化。
我在getData
功能console.log中获取数据值
这是我正在使用的脚本。
<script type="text/javascript">
$(document).ready(function(){
function getData(){
$.ajax({
type: 'GET',
url: 'data.php',
success: function(data){
// var number = document.write(data) ;
console.log(data);
return data ;
}
}) ;
}
Highcharts.chart('chart', {
chart: {
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load: function () {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function () {
var x = (new Date()).getTime(), // current time
y = getData();
console.log(y);
series.addPoint([x, y], true, true);
}, 1000);
}
}
},
time: {
useUTC: false
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
headerFormat: '<b>{series.name}</b><br/>',
pointFormat: '{point.x:%Y-%m-%d %H:%M:%S}<br/>{point.y:.2f}'
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'Random data',
data: (function () {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i += 1) {
data.push({
x: time + i * 1000,
y: getData()
});
}
return data;
}())
}]
});
});
</script>
现在您可以看到我已经创建了一个getData函数并获取了数据值作为回报。
在控制台日志上的getData函数下,我每秒钟获取一次整数值作为回报。
问题是在Highchart函数下,我无法使用getData函数获取数据值,它在控制台中返回undefined。
Highchart正在运行,但未显示任何数据点。它正在移动,但未显示任何数据点。
请在我做错的地方纠正我。
任何帮助表示赞赏。谢谢
最佳答案
ajax调用是异步运行的,因此您无法真正从中返回数据。
相反,您应该在ajax成功函数中呈现图表。
一个很好的例子已经在这里。
https://www.highcharts.com/docs/working-with-data/live-data
基本上
1.在加载点上调用函数getData
2.在Getdata中调用ajax函数。
3.成功的ajax呈现带有新数据的图表。
document.addEventListener('DOMContentLoaded', function() {
chart = Highcharts.chart('container', {
chart: {
type: '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: []
}]
});
});
/**
* 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(point, true, shift);
// call it again after one second - add this if you want to auto refresh
// setTimeout(requestData, 1000);
},
cache: false
});
}
关于javascript - Highcharts 不显示函数的数据值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57766658/