文章出處

我們都知道ajax可以做異步提交,可以從一個文件里得到返回的數據,如此便能夠實時的得到數據,實時刷新頁面,如下代碼

setInterval(function(){
    $.ajax({
        url:'demo_sse.php',
        type:'get',
        dataType:'text',
        success:function(msg){
            console.log(msg);
        }
    })
}, 3000);

第二種方法:

可以通過html 的一個函數 EventSource來實現這個功能。代碼如下:

<div data-role="footer">
        <?php
        /**
         * 登陸名單
         */
        include_once "common/conn.php";       
        ?>
        <h3 style="text-align: center;">已登錄<span id="countNum"></span></h3>
    </div>
<script>
    //監聽人數
    //HTML 服務器發送事件
    if(typeof(EventSource)!=="undefined")
    {
        var source=new EventSource("login.php");
        source.onmessage=function(event)
        {
            console.log($.trim(event.data));
            $("#countNum").text($.trim(event.data));
        };
    }
    else
    {
        console.log("Sorry, your browser does not support server-sent events...");
    }
</script>

以下是login.php的內容

<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header("Access-Control-Allow-Origin: *");
//鏈接數據庫
include_once "common/conn.php";
$lastEventId = floatval(isset($_SERVER["HTTP_LAST_EVENT_ID"]) ? $_SERVER["HTTP_LAST_EVENT_ID"] : 0);
if ($lastEventId == 0) {
    $lastEventId = floatval(isset($_GET["lastEventId"]) ? $_GET["lastEventId"] : 0);
}
//得到登陸人數
$query1 = "select count(*) from user where islogin=1";
$result = mysql_query($query1) or die('Query failed: ' . mysql_error());
$line = mysql_fetch_row($result);

$pa = $line[0];
$time = date('r');
echo "data: {$pa}\n\n";
ob_flush();
flush();
sleep(1);//sleep() 函數延遲代碼執行1秒。
?>

 

留待以后參考。。。

 


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()