如何使用Python(具有websockets的服务器)和JavaScript(客户端)接收JSON数据 [英] How to receive JSON data with Python (server with websockets) and JavaScript (client-side)

查看:1064
本文介绍了如何使用Python(具有websockets的服务器)和JavaScript(客户端)接收JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a newbie question with receiving JSON data from Python working as a server. I need to tell you that the server is based on WebSockets and I'm sending JSON data from Python to JavaScript successfully but I can't find any source how to proceed with this data to parse this and show it in different divs like value of the first_name in the id="message-1" div, second_name in the message2 div etc. Could you help me figure this out? Here is the code and picture what my firefox return: Web page.

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

I almost forgot to mention that I'm using localhost with xampp or ngrok to "host" my client-side. Also, there is a connection because I'm receiving logs on the website as well as in python console

先谢谢您了:)

这是python代码:

Here is python code:

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代码

Here is HTML/JS code

<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>

推荐答案

您需要解析收到的消息并将其附加到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,将'(单引号)替换为"(双引号):

Remember JSON Needs to be valid json, Replace ' (single-quote) with " (double-quote):

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

这篇关于如何使用Python(具有websockets的服务器)和JavaScript(客户端)接收JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆