前言
我前面文章講過數(shù)據(jù)大屏,里面的數(shù)據(jù)時(shí)時(shí)更新。還有時(shí)時(shí)更新的股票數(shù)據(jù),F(xiàn)acebook/Twitter 更新、估價(jià)更新、新的博文、賽事結(jié)果等等,都需要數(shù)據(jù)時(shí)時(shí)更新。之前我們一般都是請(qǐng)求服務(wù)器,看看有沒有可以更新的數(shù)據(jù)。html5提供了Server-Sent Events方法,通過服務(wù)器發(fā)送事件,更新能夠自動(dòng)到達(dá)。
Server-Sent Events使用
Server-Sent Events使用很簡(jiǎn)單,通過EventSource 對(duì)象來接受服務(wù)器端消息。有如下事件:
檢測(cè) Server-Sent 事件支持
if(typeof(EventSource)!=="undefined"){ // 瀏覽器支持 Server-Sent // 一些代碼.....}else{// 瀏覽器不支持 Server-Sent..}
接收 Server-Sent 事件通知
var source=new EventSource("haorooms_sse.php");source.onmessage=function(event){ document.getElementById("result").innerHTML+=event.data + "<br>";};
服務(wù)器端代碼實(shí)例
<?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(); ?>
鏈接事件和報(bào)錯(cuò)事件都加上
if(typeof(EventSource)!=="undefined"){ var source=new EventSource("server.php"); source.onopen=function() { console.log("Connection to server opened."); }; source.onmessage=function(event) { document.getElementById("result").innerHTML+=event.data + "<br>"; }; source.onerror=function() { console.log("EventSource failed."); };}else{ document.getElementById("result").innerHTML="抱歉,你的瀏覽器不支持 server-sent 事件...";}
我們會(huì)發(fā)現(xiàn),控制臺(tái)打印如下:
不停的進(jìn)入鏈接、和錯(cuò)誤,詳情請(qǐng)點(diǎn)擊
那是因?yàn)閜hp代碼只是簡(jiǎn)單的echo,并沒有連續(xù)輸出,我們把上面php代碼做如下改進(jìn)
<?php header('Content-Type: text/event-stream'); header('Cache-Control: no-cache'); $time = date('r'); $i = 0; $c = $i + 100; while (++$i < $c) { echo "id: " . $i . "/n"; echo "data: " . $time. ";/n/n"; ob_flush(); flush(); sleep(1); }?>
就不會(huì)出現(xiàn)不停錯(cuò)誤了!
IE瀏覽器兼容解決方案
我們知道,IE瀏覽器并不支持EventSource,有如下解決方案:
引入
eventsource.min.js
就可以完美解決。可以查看其github地址:https://github.com/Yaffle/EventSource 結(jié)合nodejs使用也很方便,直接
npm install event-source-polyfill
就可以了。
github地址:https://github.com/confidence68/demoOfSocket/tree/master/serversent
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VeVb武林網(wǎng)。
新聞熱點(diǎn)
疑難解答