123456789101112131415161718192021222324252627282930313233 |
- <!DOCTYPE html>
- <html>
- <head>
- <title>Server-Sent Events Demo</title>
- </head>
- <body>
- <div id="output"></div>
- <script>
- // 创建 EventSource 对象,建立 SSE 连接
- var eventSource = new EventSource('server.php');
- // 监听服务器发送的消息
- eventSource.onmessage = function(event) {
- // 在这里处理接收到的数据
- var data = event.data;
- if (data === '') {
- // 连接关闭,显示完成
- eventSource.close();
- } else {
- // 输出内容到页面上
- var outputElement = document.getElementById('output');
- outputElement.innerHTML += data + '<br>';
- }
- };
- // 监听连接关闭事件
- eventSource.onclose = function(event) {
- console.log('SSE connection closed.');
- };
- </script>
- </body>
- </html>
|