• 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语句中。

  • 相关阅读:
    on条件与where条件的区别
    Sqlserver中如何创建链接服务器
    SQL Server 2008 R2 主从数据库同步
    网站性能优化
    检索COM 类工厂中CLSID 为 {00024500-0000-0000-C000-000000000046}的组件时失败
    text输入框中按下enter键时阻止刷新页面
    关于以DataTable形式批量写入数据的案例
    关于Excel导入的HDR=YES; IMEX=1详解
    一条结合where、group、orderby的linq语法
    Linq使用Group By经验总结
  • 原文地址:https://www.cnblogs.com/RachelChen/p/5432667.html
Copyright © 2020-2023  润新知