index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" > <html xmlns= "http://www.w3.org/1999/xhtml" xml:lang= "en" > <head> <meta http-equiv= "Content-Type" content= "text/html;charset=UTF-8" > <script type= "text/javascript" src= "http://s1.hqbcdn.com/??lib/jquery/jquery-1.7.2.min.js" ></script> </head> <body> <p id= "msg" ></p> <input id= "btn" type= "button" value= "测试" /> <script type= "text/javascript" > $( function (){ $( "#btn" ).bind( "click" ,{btn:$( "#btn" )}, function (evdata){ $.ajax({ type: "POST" , dataType: "json" , url: "data.php" , timeout:80000, //ajax请求超时时间80秒 data:{time: "80" }, //40秒后无论结果服务器都返回数据 success: function (data,textStatus){ //从服务器得到数据,显示数据并继续查询 if (data.success== "1" ){ $( "#msg" ).append( "<br>[有数据]" +data.text); evdata.data.btn.click(); } //未从服务器得到数据,继续查询 if (data.success== "0" ){ $( "#msg" ).append( "<br>[无数据]" ); evdata.data.btn.click(); } }, //Ajax请求超时,继续查询 error: function (XMLHttpRequest,textStatus,errorThrown){ if (textStatus== "timeout" ){ $( "#msg" ).append( "<br>[超时]" ); evdata.data.btn.click(); } } }); }); }); </script> </body> </html> |
在这里是无限的循环,循环的结束条件就是获取到了返回结果返回Json数据。
并且接受$_POST[‘time’]参数来限制循环的超时时间,避免资源的过度浪费。(浏览器关闭不会发消息给服务器,使用可能一直循环下去)
data.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <?php if ( empty ( $_POST [ 'time' ])) exit (); set_time_limit(0); //无限请求超时时间 $i =0; while (true){ //sleep(1); usleep(500000); //0.5秒 $i ++; //若得到数据则马上返回数据给客服端,并结束本次请求 $rand =rand(1,999); if ( $rand <=15){ $arr = array ( 'success' => "1" , 'name' => 'xiaoyu' , 'text' => $rand ); echo json_encode( $arr ); exit (); } //服务器($_POST['time']*0.5)秒后告诉客服端无数据 if ( $i == $_POST [ 'time' ]){ $arr = array ( 'success' => "0" , 'name' => 'xiaoyu' , 'text' => $rand ); echo json_encode( $arr ); exit (); } } ?> |