HTML5之服务器发送事件

本文介绍了Server-Sent事件技术,这是一种使网页能自动接收服务器更新的技术。文章详细讲解了其工作原理、浏览器支持情况及使用步骤,并提供了一个具体的实例演示如何在网页中实现时间的自动更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 定义

Server-Sent 事件指的是网页自动获取来自服务器的更新

以前也可能做到这一点,前提是网页不得不询问(非自动)是否有可用的更新。通过服务器发送事件,更新能够自动到达。

例子:Facebook/Twitter 更新、估价更新、新的博文、赛事结果等。

2 浏览器支持

所有主流浏览器均支持 web worker,除了 Internet Explorer。

3.使用步骤

检测 Server-Sent 事件支持----接收 Server-Sent 事件通知


4.实例分析
在浏览器内部创建个时间自动更新,自动刷新
<span style="font-family:Arial;"><span style="font-size: 18px; line-height: 26px;"><!DOCTYPE html>//本地代码
<html>
<body>
<h1>获得服务器更新</h1>
<div id="result"></div>

<script>
if(typeof(EventSource)!=="undefined")//</span></span><h2 style="font-family: Arial; font-size: 18px; line-height: 26px; margin: 0px; padding: 0px; border: 0px; border-image-source: initial; border-image-slice: initial; border-image-width: initial; border-image-outset: initial; border-image-repeat: initial;"><span style="font-weight: normal;font-size:14px;">检测 Server-Sent 事件支持</span></h2><span style="font-family:Arial;"><span style="font-size: 18px; line-height: 26px;">
  {
  var source=new EventSource("/example/html5/demo_sse.php");//</span></span>建一个新的 EventSource 对象,然后规定发送更新的页面的 URL(本例中是 "demo_sse.php")<span style="font-family:Arial;"><span style="font-size: 18px; line-height: 26px;">
  source.onmessage=function(event)
    {
    document.getElementById("result").innerHTML+=event.data + "<br />";//</span></span><span style="font-family: Arial, Helvetica, sans-serif;">每接收到一次更新,就会发生 onmessage 事件,</span><span style="font-family: Verdana, Arial, 宋体; background-color: rgb(249, 249, 249);">当 onmessag         e 事件发生时,把已接收的数据推入 id 为 "result" 的元素中</span><span style="font-family:Arial;"><span style="font-size: 18px; line-height: 26px;">
    };
  }
else
  {
  document.getElementById("result").innerHTML="Sorry, your browser does not support server-sent events...";
  }
</script>

</body>
</html></span></span>//以下为服务器代码<span style="font-family:Arial;"><span style="font-size: 18px; line-height: 26px;">
</span></span>
<pre name="code" class="javascript"><?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

$time = date('r');
echo "data: The server time is: {$time}\n\n";
flush();
?>


 
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值