相关文章推荐
酷酷的煎鸡蛋  ·  Golang WebSocket Ping ...·  1 周前    · 
睿智的墨镜  ·  Glibc ...·  1 年前    · 
听话的小刀  ·  Android ...·  1 年前    · 
谦和的猕猴桃  ·  linux screen ...·  1 年前    · 

html使用websocket接收python后端的json数据前端显示

119浏览 · 2024-03-19 15:44:25
您可以使用JavaScript的WebSocket API来在[前端](https://geek.csdn.net/educolumn/05912bd060ca90422c50807bd9f5e9fb?spm=1055.2569.3001.10083)页面上接收Python[后端](https://geek.csdn.net/educolumn/1b483a4a3530863b540ab6ef16d99a2a?spm=1055.2569.3001.10083)的JSON数据,并将其[显示](https://geek.csdn.net/educolumn/103ca72607c717122e068b9f06a24df6?spm=1055.2569.3001.10083)在页面上。下面是一个简单的例子: 1. 编写HTML[代码](https://geek.csdn.net/educolumn/1572ef9b473b4e00f6b2bf6d428b7c27?spm=1055.2569.3001.10083): ```html <!DOCTYPE html> <title>WebSocket Example</title> <script> var socket = new WebSocket("ws://localhost:8000/ws/"); socket.onopen = function(event) { console.log("WebSocket opened"); socket.onmessage = function(event) { var data = JSON.parse(event.data); console.log(data); // 在页面上[显示](https://geek.csdn.net/educolumn/103ca72607c717122e068b9f06a24df6?spm=1055.2569.3001.10083)数据 document.getElementById("data").innerHTML = data.message; socket.onerror = function(event) { console.log("WebSocket error"); socket.onclose = function(event) { console.log("WebSocket closed"); </script> </head> <h1>WebSocket Example</h1>