js发起长轮询获取推送消息
<!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8"> <title></title> <script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/1.8.1/jquery.min.js"></script> </head> <body> <div class="tmp">123</div> <script type="text/javascript"> // post 请求 function clin_post(){ $.post("test.php",function(data){ $('.tmp').html(data); clin_post(); },'json'); } clin_post(); </script> </body> </html>
用js发起请求的回调中再次发起请求 即可得到一个轮询
php服务端可以用时间限制
<?php $start_time = time(); $num = 5; $diff_time = 0; while( ($num - $diff_time)>0 ) { $now = time(); $diff_time = $now - $start_time; } echo json_encode(date('Y-m-d H:i:s'));?>
或者直接用sleep函数
<?php sleep(5); echo json_encode(date('Y-m-d H:i:s')); ?>