<!DOCTYPE HTML><HTML><Head><MetaCharSet= "Utf-8"><Metahttp-equiv= "X-ua-compatible"content= "Ie=edge"><Metacontent= "text/html; charset=utf-8"http-equiv= "Content-type"><title>Comet Test</title><Scriptsrc=".. /statics/js/jquery-1.9.1.min.js "></Script></Head><Body><Scripttype= "Text/javascript">$(function(){ functionHandleresponse (response) {$ ('#content'). Append ('<div>' +response['msg'] + '</div>'); } vartimestamp= 0; varURL= 'server.php'; varNoError= true; varAjax; functionConnect () {Ajax=$.ajax (URL, {type:'Get', data: {'timestamp': Timestamp}, Success:function(transport) {eval ('var response ='+transport); Timestamp=response['timestamp']; Handleresponse (response); NoError= true; }, Complete:function(transport) {(!noerror)&&SetTimeout (function() {Connect ()}, the) ||Connect (); NoError= false; } }); } functiondorequest (Request) {$.ajax (URL, {type:'Get', data: {'msg': Request}}); }; $('#cometForm'). On ("Submit",function() {dorequest ($ ('#word'). Val ()); $('#word'). Val ("'); return false; }); Connect ();});</Script><DivID= "Content"></Div><Divstyle= "margin:5px 0;"><formAction= "javascript:void (0);"ID= "Cometform"Method= "Get"><inputID= "word"name= "word"type= "text"value=""><inputname= "Submit"type= "Submit"ID= "BTN"value= "Send"> </form></Div></Body></HTML>
<?PHP$filename= ' F:\phpStudy\WWW\boss\cometDemo\data.txt ';//messages are stored in this file.$msg=isset($_get[' msg ']) ?$_get[' msg ']: ';if($msg! = "){ //fopen () method: If the file does not exist, it is created, if it exists, the file is opened. Its second parameter is the open file mode, w means the overlay is write-only, see PHP elevation design 183 page $FN=fopen($filename, ' W '); fwrite($FN,$msg); fclose($FN);//file_put_contents ($filename, $msg); This method is not recommended for use } //keep looping until the file that stores the message is modified $lastmodif=isset($_get[' timestamp ']) ?$_get[' timestamp ']: 0; $currentmodif=Filemtime($filename); while($currentmodif<=$lastmodif){//If the data file has been modified Usleep(100000);//100ms pause to relieve CPU pressure Clearstatcache();//Clearing Cache information $currentmodif=Filemtime($filename); } //returns a JSON array $response=Array(); $response[' msg '] =file_get_contents($filename); $response[' timestamp '] =$currentmodif; EchoJson_encode ($response); Flush(); ?>
Bring your own jquery1.9.1 and rewrite the path to the TXT file
My first comet long connection example