HTML5新API SSE服务器发送事件

1、介绍

      SSE是创建到服务器单向连接,服务器可以通过这个连接发送任意数量的数据。

2、基本使用

      var source = new EventSource("服务器地址")//创建一个EventSource对象

      source.onmessage = function(ev) {

              console.log(ev.data) ;     //服务器发送的数据放到ev.data中

      }

    source.onopen = function() {}

  source.onerror = function() {}

    //source.close()   关闭连接,不会再发送

// 执行顺序分别是open、message、error

php文件

<?php
header('Content-Type: text/event-stream');    // 必须
header('Cache-Control: no-cache');        //禁止浏览器缓存

$time = date('r');
echo "data: The server time is: {$time}\n\n";   //  \n\n是必须的,只有包含data: 数据 后面有空行,onmessage才会触发
flush();    

tips:服务器地址不能携带GET参数,否则无法正常执行。

3、兼容问题

由于兼容性问题,首先使用能力检测

if(EventSource) {

  var source = new EventSource("服务器地址")//创建一个EventSource对象

}else {

  //使用ajax

}   

猜你喜欢

转载自www.cnblogs.com/Salted-fish-without-dreams1/p/9451715.html
今日推荐