8. server 端 ( test.php )
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
while(1)
{
$time = date('r');
echo "data: The server time is: {$time}nn";
flush();
sleep(3);
}
?>
9. Client端 ( index.html )
<script>
if (window.EventSource)
{
var source = new EventSource('test.php');
source.onmessage = function(event)
{
$("#result").innerHTML += event.data;
};
}
else
//瀏覽器不支援 SSE,使用傳統的 xhr polling
</script>
The server time is: Sun, 15 Nov 2015 12:31:10 +0000
The server time is: Sun, 15 Nov 2015 12:31:13 +0000
The server time is: Sun, 15 Nov 2015 12:31:16 +0000
The server time is: Sun, 15 Nov 2015 12:31:19 +0000
The server time is: Sun, 15 Nov 2015 12:31:22 +0000
…………………..