index.html 772 B

123456789101112131415161718192021222324252627282930313233
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Server-Sent Events Demo</title>
  5. </head>
  6. <body>
  7. <div id="output"></div>
  8. <script>
  9. // 创建 EventSource 对象,建立 SSE 连接
  10. var eventSource = new EventSource('server.php');
  11. // 监听服务器发送的消息
  12. eventSource.onmessage = function(event) {
  13. // 在这里处理接收到的数据
  14. var data = event.data;
  15. if (data === '') {
  16. // 连接关闭,显示完成
  17. eventSource.close();
  18. } else {
  19. // 输出内容到页面上
  20. var outputElement = document.getElementById('output');
  21. outputElement.innerHTML += data + '<br>';
  22. }
  23. };
  24. // 监听连接关闭事件
  25. eventSource.onclose = function(event) {
  26. console.log('SSE connection closed.');
  27. };
  28. </script>
  29. </body>
  30. </html>