下面是实现Smoothie.js实时流图表的超文本标记语言文档。就其本身而言,timeSeries.append()和getJSON()方法工作得很好,但是timeSeries.append()似乎不允许使用JSON数据值。
程序卡在count()函数中;我添加了一个document.write()方法来查看它是否会输出(见下文),但它没有。
我想可能是因为JSON的数据。解析时,将是一个字符串。所以我把数据变成了一个字符串,然后是一个整型。
但这并不管用。
我一直在尝试,没有什么能像我需要的那样有效
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Click to open the live PeopleCount chart </button>
<script src="https://cdn.rawgit.com/Manaal123/smoothie/master/smoothie.js"></script>
<canvas id="chart" width="700" height="350"></canvas>
<style>
div.smoothie-chart-tooltip {
background: #999;
padding: 1em;
margin-top: 20px;
font-family: consolas;
color: white;
font-size: 17px;
pointer-events: none;
}
</style>
<script>
var chart = new SmoothieChart({
interpolation: 'step',
grid: {
fillStyle: '#ffffff',
strokeStyle: '#c0c0c0',
verticalSections: 10
},
labels: {
fillStyle: '#000000',
fontSize: 16,
precision: 0
},
tooltip: true,
maxValue: 10,
minValue: 0,
timestampFormatter: SmoothieChart.timeFormatter
}),
timeSeries = new TimeSeries();
chart.addTimeSeries(timeSeries, {
strokeStyle: 'blue',
lineWidth: 1,
fillStyle: 'rgba(0,128,255,0.30)'
});
function count() {
$.getJSON("http://192.168.20.193:8001/count", function(result) {
temp = result.data.count;
});
document.write("hi");
temp = parseInt(temp, 10);
return temp;
}
function myFunction() {
chart.streamTo(document.getElementById('chart'), 100);
setInterval(function() {
timeSeries.append(new Date().getTime(), count());
}, 5000);
}
var temp;
</script>
</body>
</html>
发布于 2018-08-04 11:00:39
count()返回undefined,因为$.getJSON是异步的,而您在回调中设置它之前返回了temp。我会将count()重写为类似这样的内容
function count(callback) {
$.getJSON("http://192.168.20.193:8001/count", function(result) {
return callback(parseInt(result.data.count, 10));
});
}现在您有办法知道count(...)何时结束(何时调用回调函数)
然后我会重写你所说的方式
setInterval(function() {
count(function(temp){
timeSeries.append(new Date().getTime(), temp);
})
}, 5000);这样做可以确保您在图表上设置数据之前等待对服务器的请求完成。如果你想了解更多,我建议你用谷歌搜索一下asynchronous这个词。
https://stackoverflow.com/questions/51681084
复制相似问题