javascript - 如何使用 js 将 json 发送到 websockets 中的客户端并打印值?
问题描述
我想从服务器解析这样的json
{"prevCount":0, "addition":5, "type":"small"}
我用这种方式尝试了更多值,但它不起作用我想实时计算它,所以一旦它们在服务器中更改值,也应该更新客户端
这是我的服务器
server.on('connection', function(ws) {
console.log('connected');
ws.on('message', function(data, flags) {
console.log('received: ' + util.inspect(data));
//ws.send(data, { binary: flags.binary });
ws.send(JSON.stringify({"prevCount":0, "addition":5, "type":"small"}))
});
ws.on('close', function() {
console.log('close');
});
});
客户留言
// Handle incoming websocket message callback
ws.onmessage = function(evt) {
log("Message Received: " + evt.data)
//alert("message received: " + evt.data);
var obj = JSON.parse(evt.data);
var type = obj.type;
var prevCount = obj.prevCount;
var addition = obj.addition;
if(obj.type==small){
$('td#sCount').text(obj.prevCount + obj.addition)
}
if(obj.type==medium){
$('td#mCount').text(obj.prevCount + obj.addition)
}
if(obj.type==large){
$('td#lCount').text(obj.prevCount + obj.addition)
}
if(obj.type==twol){
$('td#2lCount').text(obj.prevCount + obj.addition)
}
};
我的html代码
<td style="width: 164px; height: 55px;">Small</td>
<td style="width: 273px; height: 55px;" id="sCount"> </td>
</tr>
<tr style="height: 55px;">
<td style="width: 164px; height: 55px;">Medium</td>
<td style="width: 273px; height: 55px;" id="mCount"> </td>
</tr>
<tr style="height: 55px;">
<td style="width: 164px; height: 55px;">Large</td>
<td style="width: 273px; height: 55px;" id="lCount"> </td>
</tr>
输出应该是这样的:
- 小 - 总计
- 中等 - 总计
- 大 - 总计
但是我的代码不起作用,表格列中没有任何内容
任何帮助表示赞赏
注意-client 在 jquery 中
我找到了这个 How to receive JSON data with Python (server with websockets) and JavaScript (client-side)
我从中得到了一个想法,但它的服务器在 python 上,我的是 js,没用
解决方案
推荐阅读
- php - PHP奇怪的花括号语法?
- json - 使用 Alexa 的 HTTP-Endpoint 在 APL 中可视化列表
- python - 并行(代理)请求并获得最快的结果
- python - 在隔离林中应该根据什么标准选择引导参数?
- rust - 为什么 Rust 允许升级/降级可变性?
- sql - 如何在 redshift 的子查询中使用外部表中的值?
- python - 如何在模板中添加条件以检测超级用户与帖子作者相同
- python - Kivy 按钮类不执行后续命令
- python - Python FlaskKafka - 总线线程上的异常会杀死线程,我必须重新启动应用程序
- ffmpeg - ffmpeg 平铺图像来自视频总图像计数