HTML 5 server sends events

Source: Internet
Author: User

HTML5 Server Send events (Server-sent event) allow Web pages to get updates from the server.

Browser support

All major browsers support server sending events, in addition to Internet Explorer.

Server-side Code instances

To make the above example work, you also need a server that can send data updates (such as PHP).

The syntax of the server-side event stream is very simple. Set the "Content-type" header to "Text/event-stream". Now, you can start sending an event stream

<? 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 ();? >
Receive Server-sent event notifications

The EventSource object is used to send event notifications to the receiving server:

var source=New EventSource ("demo_sse.php"); source.onmessage=function( Event)  {  document.getElementById ("result"). Innerhtml+=event.data + "<br/>";  };

Detect Server-sent Event Support

In the tiy example above, we have written an extra piece of code to detect the browser support of the server sending the event:

if (typeof(EventSource)!== "undefined")  {  //  yes! Server-sent Events support!  // Some code ... ..   }Else  {  //  sorry! No server-sent Events Support:  }

Ext.: http://www.w3school.com.cn/html5/html_5_serversentevents.asp

HTML 5 server sends events

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.