jQuery comet

 2023-09-10 阅读 22 评论 0

摘要:下面程序是例用从数据端推送信息,原理是每隔10秒读取一下data.txt文件,看有木有新的数据输入,如果有,则alert文件内容。 hmtl代码是 <!DOCTYPE html> <html> <head><title>Jquery Comet</title><script src=

下面程序是例用从数据端推送信息,原理是每隔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变成JSONif(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语句中。

 

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

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/5/37798.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息