首页 > 解决方案 > 如何使用 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">&nbsp;</td>
                </tr>
                <tr style="height: 55px;">
                <td style="width: 164px; height: 55px;">Medium</td>
                <td style="width: 273px; height: 55px;" id="mCount">&nbsp;</td>
                </tr>
                <tr style="height: 55px;">
                <td style="width: 164px; height: 55px;">Large</td>
                <td style="width: 273px; height: 55px;" id="lCount">&nbsp;</td>
                </tr>

输出应该是这样的:

但是我的代码不起作用,表格列中没有任何内容

任何帮助表示赞赏

注意-client 在 jquery 中

我找到了这个 How to receive JSON data with Python (server with websockets) and JavaScript (client-side)

我从中得到了一个想法,但它的服务器在 python 上,我的是 js,没用

标签: javascriptjquerywebsocket

解决方案


推荐阅读