I have talked about the large screen of the data earlier, and the data inside is updated from time to time. Sometimes the stock data updated from time to time, Facebook/Twitter update, valuation update, new blog posts, event results, etc., all need data updates from time to time. We used to ask the server to see if there are any updates. HTML5 provides the Server-Seent events method. When sending events through the server, the update can automatically reach.
Server-sevents useServer-sectionS is very simple to use, to receive server messages through the EventSource object. There are the following incidents:
if (Typeof (EventSource)! == UNDEFINED) {// Browser supports server-sent // Some code .....} else {// browser does not support server-sent ..} Receive the server-sent event notice Var Source = New EventSource (haorooms_sse.php); Source.onMessage = Function (Event) {document.GetelementByid (result) .innerhtml + = event.data + << br>;}; Server side code instance <? 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 ();?> Both link events and errors add If (Typeof (EventSource)! == UNDEFINED) {var source = new eventSource (server.php); source.onopen = function () {console.log (connection to server operation d.);}; Source.onMessage = Function ( Event) {document.GetelementByid (result) .innerHtml + = Event.data + <br>; Source.onerror = Function () {console.log (eventsource failed.); } Else {document.GetelementByid (Result) .innerhtml = Sorry, your browser does not support the server-sent event ...;}We will find that the console is printed as follows:
Enter the link and errors constantly, please click on details
That's because the PHP code is just a simple Echo, and there is no continuous output.
<? PHP Header ('Content-Type: Text/Event-Stream'); Header ('Cache-Control: No-Cache'); $ Time = Date ('R'); $ i = 0; I+100; While (++ $ i <$ C) {echo ID:. $ i./n; echo data:. $ Time.;/n/n; ob_flush (); flush (); Sleep (1) ;}?>There will be no non -stop errors!
IE browser compatibility solutionWe know that the IE browser does not support EventSource, and there are the following solutions:
Introduceeventsource.min.js
It can be perfectly solved. You can view its github address: https://github.com/yaffle/eventsource binding nodejs is also very convenient.
NPM Install Event-Source-POLYFILL
That's fine.
github Address: https://github.com/confidence68/demoofsocket/tree/master/serversnt
The above is all the contents of this article. I hope it will be helpful to everyone's learning. I also hope that everyone will support VEVB Wulin.com.