AJAX新宠-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。下个版本更新。

 实例代码点击下载

 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值