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

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.

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

Thanks in advance :)

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

Here is HTML/JS code

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

};

解决方案

You need to parse the message you received and attach it to the 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);

}

}

If this is not working, then check the json format your are sending!

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

d = {

"first_name": "Guido",

"second_name": "Rossum",

"titles": ["BDFL", "Developer"]

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值