静态页面局部刷新.html 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <html>
  2. <head>
  3. <style>
  4. #server-info {
  5. width:50%;
  6. height:20%;
  7. font-size:40px;
  8. /* border:1px solid red; */
  9. }
  10. #textarea {
  11. width:100%;
  12. height:auto;
  13. /* border:1px solid red; */
  14. }
  15. /* p {color:blue} */
  16. </style>
  17. </head>
  18. <body>
  19. <div Id = 'server-info'>服务器返回信息</div>
  20. <div Id = 'textarea'>
  21. <textarea Id="textarea_id" rows="30" cols="120"></textarea>
  22. </div>
  23. <script>
  24. let str = '';
  25. // var ws = new WebSocket("ws://localhost:3000");
  26. // var ws = new WebSocket("ws://121.4.59.141:3000/node/");
  27. var ws = new WebSocket("ws://www.yuyekeji.cn:3000/node/");
  28. console.log("WebSocket建立成功");
  29. //申请一个WebSocket对象,参数是服务端地址,同http协议使用http://开头一样,WebSocket协议的url使用ws://开头,另外安全的WebSocket协议使用wss://开头
  30. ws.onopen = function () {
  31. //当WebSocket创建成功时,触发onopen事件
  32. console.log("open");
  33. document.getElementById("server-info").innerHTML = "已建立服务端连接!"
  34. ws.send('{"name":"22","type":"login","user_name":"","message":""}'); //将消息发送到服务端
  35. }
  36. ws.onmessage = function (e) {
  37. //当客户端收到服务端发来的消息时,触发onmessage事件,参数e.data包含server传递过来的数据
  38. console.log(e.data);
  39. let data_json = JSON.parse(e.data);
  40. document.getElementById("server-info").innerHTML = '收到来自“'+data_json.name+'”的消息:<br />'+data_json.message;
  41. str=str+data_json.message+'\n';
  42. // 给文本框赋值
  43. document.getElementById("textarea_id").value = str;
  44. // 跳转最后一行
  45. document.getElementById("textarea_id").scrollTop=document.getElementById("textarea_id").scrollHeight;
  46. }
  47. ws.onclose = function (e) {
  48. //当客户端收到服务端发送的关闭连接请求时,触发onclose事件
  49. console.log("close");
  50. }
  51. ws.onerror = function (e) {
  52. //如果出现连接、处理、接收、发送数据失败的时候触发onerror事件
  53. console.log(error);
  54. }
  55. </script>
  56. </body>
  57. </html>