如何使用Python(带有Websocket的服务器)和JavaScript(客户端)接收JSON数据

时间:2018-07-13 11:02:47

标签: javascript python json websocket

我有一个新手问题,就是从作为服务器的Python接收JSON数据。我需要告诉你服务器是基于WebSockets的,并且我已经成功地将JSON数据从Python发送到JavaScript,但是我找不到任何来源如何处理该数据并将其显示在不同的div中,例如value of first_name id="message-1"中的divsecond_name message2中的div等。您能帮我解决这个问题吗?这是我的Firefox返回的代码和图片:Web page

我几乎忘了提到我将localhost与xampp或ngrok一起使用来“托管”客户端。另外,有一个连接是因为我在网站以及python控制台中都收到日志

预先感谢:)

这是python代码:

import asyncio
import websockets
import json


async def time(websocket, path):
    while True:
        d = {'first_name': 'Guido',
             'second_name': 'Rossum',
             'titles': ['BDFL', 'Developer'],
             }
        parsed = json.dumps(d)
        name = "Jeremy"
        # now = datetime.datetime.utcnow().isoformat() + 'Z'
        for i in range(1):
            await websocket.send(parsed)
            response = await websocket.recv()
            print(response)
        start_server = websockets.serve(time, '127.0.0.1', 4040)


asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

这是HTML / JS代码

<body>
<div id="message-1"></div>
<div id="message-2"></div>
<div id="message-3"></div>
<script>
    var ws       = new WebSocket("ws://127.0.0.1:4040/");
    ws.onopen    = function () {
        ws.send('Hello, Server!!');
        //send a message to server once ws is opened.
        console.log("It's working onopen log / awake");
    };
    ws.onmessage = function (event) {
        if (typeof event.data === "string") {
            // If the server has sent text data, then display it.
            console.log("On message is working on log with onmessage :)");
            var label       = document.getElementById("message-1");
            label.innerHTML = event.data;
        }
    };
    ws.onerror   = function (error) {
        console.log('Error Logged: ' + error); //log errors
    };
</script>
</body>

1 个答案:

答案 0 :(得分:1)

您需要解析收到的消息并将其附加到dom!

ws.onmessage = function (event) {
    try {
        var obj  = JSON.parse(event.data);
        document.getElementById("message-1").innerHTML = obj.first_name;
        document.getElementById("message-2").innerHTML = obj.second_name;
        document.getElementById("message-3").innerHTML = obj.titles.join(" ");
    } catch {
        console.log("Object is not received, Message is:: ", event.data);
    }
}

如果这不起作用,请检查您发送的json格式!

  

记住JSON需要为有效的json,将'(单引号)替换为"(双引号):

d = {
    "first_name": "Guido",
    "second_name": "Rossum",
    "titles": ["BDFL", "Developer"]
}