duanmie9682 2014-01-20 00:08 采纳率: 100%
浏览 31
已采纳

服务器使用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 2014-01-20 00:23
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划