您的位置:首页 > Web前端 > JQuery

jQuery comet

2016-04-25 20:47 501 查看
下面程序是例用从数据端推送信息,原理是每隔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语句中。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: