1 Flash/Java Applet + Javascript
2 Pure Javascript
纯javascript实现网上有一个 prototype implements 。本文用mootools改写的实现
Comet = new Class({
initialize : function(url,param,httpMethod,timeOut){
this.url = url;
this.param = param || {};
this.type = httpMethod || 'get' ;
this.timeout = timeOut || 2*1000 ;
}
}).extend(new Events);
Comet.implement({
ajax : null,
stamp : '0',
connect : function(){
this.ajax = new XHR({
'method' : this.type,
'onSuccess' : this.success.bind(this),
'onFailure' : this.failure.bind(this)
}
);
this.param.stamp = this.stamp;
this.ajax.send(this.url,Object.toQueryString(this.param));
},
success : function(response){
var r = this.evalJSON(response);
if(typeof r === 'string') {
this.fireEvent('timeout',r);
} else {
this.stamp = r['stamp'] || this.stamp;
this.fireEvent('ready',r);
}
this.connect.delay(this.timeout,this);
},
failure : function(response){
(function(){this.connect();}).delay(this.timeout,this);
},
evalJSON: function(response) {
try { return Json.evaluate(response);} catch (e) { return response;}
}
}
);用法很简单,
cm = new Comet(url);
cm.connect();
//so you can add your event handler when accept any data from server
cm.addEvent('ready',function(r){ alert(r) });发表于 @ 2008年01月25日 14:30:00 | 评论( loading... ) | 举报| 收藏