传说中的comet(ajax版)?
不知道这是不是就是传说中的comet,感觉和普通的ajax没什么区别。也许这并不是,也许只是后台代码的区别。
demo下载:comet-ajax.zip
HTML代码:
View Code
<div id="content">
</div>
<p>
<form action="" method="get">
<input type="text" name="word" id="word" value="" />
<input type="button" id="send" name="send" value="Send" />
<input type="button" id="stop" name="stop" value="stop" />
</form>
</p>
JS代码(用的jquery):
View Code
var Comet = function(options){
this.init(options);
};
Comet.prototype = {
constructor: Comet,
init:function(options){
this.options = {
url:"",
callback:function(){}
}
this.options = $.extend(this.options,options||{});
this.url = this.options.url;
this.callback = this.options.callback;
this.timestamp = 0;
this.noerror = true;
this.lock = true;
},
connect: function(){
this.lock = false;
this.ajaxLoop();
},
disconnect: function(){
this.lock = true;
},
ajaxLoop: function(){
if(this.url && !this.lock){
var _this = this;
$.ajax({
url:_this.url,
type:'get',
data:'timestamp=' + _this.timestamp,
dataType:'json',
cache:false,
success:function(json){
_this.timestamp = json['timestamp'];
_this.handleResponse(json);
_this.noerror = true;
},
complete:function(){
if (_this.noerror){
_this.ajaxLoop();
}else{
// if a connection problem occurs, try to reconnect each 5 seconds
setTimeout(function(){_this.ajaxLoop()}, 5000);
}
_this.noerror = false;
}
})
}
},
handleResponse: function(response){
this.callback(response);
},
doRequest: function(request){
if(this.url && !this.lock){
$.get(this.url, { 'msg': request } );
}
}
}
var comet = new Comet({
url:'./backend.php',
callback:function(response){
$('#content').append('<div>' + response['msg'] + '</div>');
}
});
comet.connect();
$("#send").click(function(){
comet.doRequest($('#word').val());
$('#word').val('');
})
$("#stop").click(function(){
comet.disconnect();
})
php代码:
View Code
<?php
$filename = dirname(__FILE__).'/data.txt';
// store new message in the file
$msg = isset($_GET['msg']) ? $_GET['msg'] : '';
if ($msg != '')
{
file_put_contents($filename,$msg);
die();
}
// infinite loop until the data file is not modified
$lastmodif = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
$currentmodif = filemtime($filename);
while ($currentmodif <= $lastmodif) // check if the data file has been modified
{
usleep(10000); // sleep 10ms to unload the CPU
clearstatcache();
$currentmodif = filemtime($filename);
}
// return a json array
$response = array();
$response['msg'] = file_get_contents($filename);
$response['timestamp'] = $currentmodif;
echo json_encode($response);
flush();
?>