[英]Making a simple real-time graph
I'm trying to fetch some data from the database and plot it into a real-time graph. 我正在尝试从数据库中获取一些数据并将其绘制到实时图形中。 I'm using this as an example: http://www.flotcharts.org/flot/examples/ajax/index.html
我以这个为例: http : //www.flotcharts.org/flot/examples/ajax/index.html
THE JSON is like this: JSON是这样的:
"networks": {
"eth0": {
"rx_bytes": 5338,
"rx_dropped": 0,
"rx_errors": 0,
"rx_packets": 36,
"tx_bytes": 648,
"tx_dropped": 0,
"tx_errors": 0,
"tx_packets": 8
}
}
But my code doesn't plot anything even tho the rx_bytes
array has data inside. 但是,即使
rx_bytes
数组内部有数据,我的代码也不会绘制任何内容。 What am I missing here? 我在这里想念什么?
var rx_bytes = [], tx_bytes = [], cpu = [], mem = []; //Options var options = { lines: { show: true }, points: { show: true }, xaxis: { tickDecimals: 0, tickSize: 1 } }; //Initial Plot $.plot("#cpuStats", rx_bytes, options); $.plot("#memStats", mem, options); $.plot("#networkStats", cpu, options); function getStatistics() { $.ajax({ url: '/getStatistics', type: 'post', dataType: 'json', success: function (statistics) { console.log(statistics); var network = statistics.networks.eth0; rx_bytes.push(network.rx_bytes); console.log(rx_bytes); //Plot $.plot("#cpuStats", rx_bytes, options); //get data again getStatistics(); } }); } getStatistics();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="http://www.flotcharts.org/flot/jquery.flot.js"></script>
You need a X value for each new data point. 每个新数据点都需要一个X值。 In this case you probably want a timestamp.
在这种情况下,您可能需要时间戳记。 Also, don't call getStatistics() inside your success handler.
另外,不要在成功处理程序中调用getStatistics()。 It may lead to too much recursion.
它可能导致过多的递归。 Instead use setTimeout()
而是使用setTimeout()
success: function (statistics) {
var network = statistics.networks.eth0;
var now = new Date().getTime();
rx_bytes.push([now, network.rx_bytes]);
$.plot("#cpuStats", rx_bytes, options);
setTimeout(getStatistics, 1000);
}
This updates once per second. 每秒更新一次。
Here's a more robust jsFiddle example that also handles the initial period where data hasn't filled the X axis and also drops old data once that period expires. 这是一个更可靠的jsFiddle示例 ,该示例还处理数据未填充X轴的初始时间段,并且在该时间段到期后还会删除旧数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.