html5 + php 实现实时推送消息

  1. html页面basic_sse.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>数据推送</title>
</head>
<body>
    <pre id="result">
        Initializing...
    </pre>
    <script type="text/javascript">

        if(typeof(EventSource)!=="undefined")
          {
          var source = new EventSource("/sjts/index.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>
</body>
</html>
  1. php页面index.php

<?php
    header('Content-Type:text/event-stream');//通知浏览器开启事件推送功能
    header('Cache-Control:no-cache');//告诉浏览器当前页面不进行缓存

    //$time = date('r');
    //echo "data: The server time is: {$time}\n\n";
    
    $mysqli = new MySQLi('localhost','root','','test');
    $sql = 'select ac_id from article_class where ac_name="11";';
    $result = $mysqli->query($sql);
    while($row = $result->fetch_assoc()){
        $time = $row['ac_id'];    
        echo "data: The server time is: {$time}\n\n";
    }

    ob_flush();//刷新
    flush();//刷新
?>

总结:通过改变数据库ac_id自动,前端不刷新即可实施改变数据

    原文作者:金俸毅
    原文地址: https://segmentfault.com/a/1190000009388028
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞