html5 + PHP 推送服务

作者: jaclon 分类: JS, PHP, 程序开发 发布时间: 2013-09-12 13:49 ė 6没有评论

HTML5 server-sent事件模型允许你从服务器push实时数据到浏览器,通过EventSource对象接收数据并写到页面中,下面是一个基于HTML5+JavaScript为客户端,PHP作为服务端的案例:

客户端

<!DOCTYPE HTML>
<html lang="en-US">
<head>
	<meta charset="UTF-8">
	<title></title>
</head>
<body>
   <div id="serverData">Here is where the server sent data will appear</div>
	<script type="text/javascript">
    //check for browser support
    if(typeof(EventSource)!=="undefined") {
        //create an object, passing it the name and location of the server side script
        var eSource = new EventSource("html5_push.php");
        //detect message receipt
        eSource.onmessage = function(event) {
            //write the received data to the page
            document.getElementById("serverData").innerHTML = event.data;
        };
    }
    else {
        document.getElementById("serverData").innerHTML="Whoops! Your browser doesn't receive server-sent events.";
    }
    </script>
</body>
</html>

PHP服务端

<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$new_data = rand(0, 1000);
echo "data: New random number: $new_data\n\n";
ob_flush();
%>

本文出自 肥蕉博客@IT技术,热门话题,生活随笔,美图欣赏,转载时请注明出处及相应链接。

本文永久链接: http://www.bananawolf.com/html/2013/09/953.html

发表评论

电子邮件地址不会被公开。 必填项已用*标注

*

Ɣ回顶部