duanmie9682
duanmie9682
采纳率100%
2014-01-20 00:08

服务器使用PHP发送事件

已采纳

I can't seem to find any good example of server sent events.

My goal is to send 2 messages to 2 separate divs but i'm new with javascript so i don't know how to parse these two messages, can anyone point me in right direction?

And if someone can explain me how SSE works, can I run this php script send.php to push updates to web page or javascript runs script itself?

Here is my PHP code:

<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

$message = $row['message'];
$user = $row['user'];
echo "{$message}

";
echo "{$user}

";
flush();
?>

And this is my HTML/Javascript:

<div id="result"></div>

<script>
if(typeof(EventSource)!=="undefined")
{
var source=new EventSource("send.php");
source.onmessage=function(event)
{
document.getElementById("result").innerHTML+=event.data + "<br>";
};
}
else
{
document.getElementById("result").innerHTML="Sorry, your browser does not support server-sent events...";
}
</script>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • douyanyan1123 douyanyan1123 7年前

    You can just send the events back to the server as a JSON encoded string and indicate which div should get what message.

    $arr = array(
        'user' => $row['user'],
        'message' => $row['message']
    )
    echo json_encode($arr);
    

    Then, parse the JSON response from the server and perform logic against it. Let's assume the two divs have an ID of user and message

    source.onmessage=function(event){
        var $data = JSON.parse(event.data);
        for(key in obj){
            if (obj.hasOwnProperty(key)) { //ensure that we're not up in the prototype chain
                document.getElementById(key).innerHTML = $data[key];    
            }
        }
    } 
    

    The relationship here is of course that key will be either user or message. We also expect there to be 2 divs, id="user" and id="message" that we can modify the innerHTML for. This is not a requirement, but aids in simplifying the process.

    点赞 评论 复制链接分享

相关推荐