jQuery comet

下面程序是例用从数据端推送信息,原理是每隔10秒读取一下data.txt文件,看有木有新的数据输入,如果有,则alert文件内容。

hmtl代码是

<!DOCTYPE html>
<html>
<head>
    <title>Jquery Comet</title>
    <script src="jquery-1.10.2.min.js" type="text/javascript" charset="utf-8"></script>
    <script>

        var timestamp=null;

        function waitForMsg(){
            $.ajax({
                type:"get",
                url:"getData.php?timestamp="+timestamp,
                async:true,
                cache:false,

                success:function(data){
                    var json=JSON.parse(data); //将data由string变成JSON
                    if(json['msg']!=""){
                        alert(json['msg']); //显示消息
                    }
                    timestamp=json['timestamp']; //将时间设置成data返回的时间
                    setTimeout('waitForMsg()',1000); //一秒后重新执行
                    console.log(data);
                },
                error:function(XHLHttpRequest,textStatus,errorThrown){
                    alert("error:"+textStatus+"("+errorThrown+")");
                    setTimeout("waitForMsg()",1500);
                }
            });
        }

        $(document).ready(function(){
            waitForMsg();
        });
    </script>
</head>
<body>

</body>
</html>

php的代码是

<?php
    $filename=dirname(__FILE__).'/data.txt'; //打开文件,dirname返回父文件的地址

    $lastmodify=isset($_GET['timestamp'])?$_GET['timestamp']:0; //文件上次一修改的时间
    $currentmodify=filemtime($filename); //上一次数据块写入文件的时间

    while($currentmodify <= $lastmodify){ //上一次数据块写入的时间小于等于文件上一次修改的时间
        usleep(10000); //usleep以毫秒指定程序的延迟,这里是延迟十秒之后
        clearstatcache();
        $currentmodify=filemtime($filename);//更新数据块的写入时间
    };

    $response=array();
    $response['msg'] = file_get_contents($filename); //获取文件的内容
    $response['timestamp'] = $currentmodify; //将数据块写入的时间返回
    echo json_encode($response);
?>

之后如果在data.txt里面修改内容将会显示在alert语句中。

 

转载于:https://www.cnblogs.com/RachelChen/p/5432667.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值