在Python中运行一个autobahn websocket服务器并在html前端中获取json更新。当消息到达时,该值(在本例中为“temp”)显示为带有innerHTML的数字,该部分工作正常。
我们还有一个拨号图表(d3js),但更新是由代码末尾的setInterval函数启动的,这远非理想。如何通过websocket使测量仪更新“onmessage”?
<script type="text/javascript">
//---the websocket part--
var sock = null;
var displaynumber = null;
var tempdata = null;
window.onload = function () {
var wsuri;
displaynumber = document.getElementById('disp');
if (window.location.protocol === "file:") {
wsuri = "ws://...:9000";
} else {
wsuri = "ws://" + window.location.hostname + ":9000";
}
//set up a new websocket
if ("WebSocket" in window) {
sock = new WebSocket(wsuri);
} else if ("MozWebSocket" in window) {
sock = new MozWebSocket(wsuri);
} else {
disp("Browser does not support WebSocket!");
window.location = "http://autobahn.ws/unsupportedbrowser";
}
if (sock) {
//sock.onopen = function() {};
sock.onclose = function(e) {
sock = null;
};
sock.onmessage = function(e) {
// e.data will be sent as a string and need to be converted to object
var jsondata = JSON.parse(e.data);
tempdata = jsondata.temp;
disp(tempdata + " C");
};
}
function disp(m) {
displaynumber.innerHTML = m;
}
//----This is the dial chart part
dialChart();
function dialChart() {
var powerGauge = gauge('#power-gauge', {
size: 300,
clipWidth: 300,
clipHeight: 300,
ringWidth: 60,
minValue: 0,
maxValue: 100,
transitionMs: 1000,
});
powerGauge.render();
function updateReadings() {
powerGauge.update(tempdata);
}
updateReadings();
setInterval(function() {
updateReadings();
}, 2 * 1000);
}
}
</script>
答案 0 :(得分:1)
在dialChart
定义的最后,添加return powerGauge
。然后当您调用dialChart();
时,将结果保存到变量中。然后,不要在套接字回调中写入tempdata
,而是调用powerGaugeVariable.update(jsondata.temp)
。