jQuery comet
2016-04-25 20:47
501 查看
下面程序是例用从数据端推送信息,原理是每隔10秒读取一下data.txt文件,看有木有新的数据输入,如果有,则alert文件内容。
hmtl代码是
php的代码是
之后如果在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语句中。
相关文章推荐
- vs中正常IIS发布网站后css样式、图片丢失jQuery报错 $ is not defined
- 简单的jQuery动态得到下拉框的值
- jQuery获取Select选择的Text和 Value(转)
- jQuery取得select选中的值
- jquery控制css的display(控制元素的显示与隐藏)
- jQuery的封装方式与JS中new的实现原理
- js随笔,css和js禁止网页选择文本,table的class样式使得td的class样式失效,jquery获得元素坐标
- jquery截取、判断字符串的长度,中英文都可
- jQuery中的ajax
- Jquery获取cookies
- jQuery点击图片弹出放大可拖动图片查看
- jquery 对特俗的几个标签的取值
- jQuery网页右侧固定层显示隐藏在线qq客服代码
- jquery $(document).ready() 与window.onload的区别
- Jquery中AJAX参数详细介绍
- jQuery操作checkbox选择
- jQuery 选择器手册
- jQuery与JS入门经典——读书笔记1
- JQuery的extend扩展方法
- jquery利用正则表达式验证密码,手机号(主要是使用方法,正则表达式网上一搜一堆)