Comet 先记下来
Comet 是ajax新的应用,通俗的讲就是能push数据到客户端。在web中,要实现push到客户端,一般有两种方法: 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) }); 还没有实现用stream形式的xmlhttpRequest。下个版本更新。 实例代码点击下载