修改prototype.js以实现xmlhttp的http-basic认证

在很多时候我们在使用ajax的时候可能都需要用到http basic认证,大家可能不知道http basic认证是什么,没有关系,其实你经常见到他,有时我们在访问网站时会弹出一个要求输入用户名密码的windows窗口,这个就是http basic认证了,prototype中的xmlhttp构建不带有这个认证,今天在做一个项目的时候,需要用到这个东西,因此我对prototype.js进行了修改,以实现此功能。
现在将我的经验与大家分享,也许可以起到抛砖引玉的作用。本文的prototype.js库使用的是本文发表时最新的版本:1.5.1.1。

因为这部分主要是对prototype的ajax部分进行修改,因此首先打开prototype,用搜索功能搜索“ajax”,定位到ajax部分,这大概是932行。我们可以看到,ajax部分开始是定义了一些基类,以方便在后面继承此类来派生新的功能。

这时我们转到985行,找到ajax.base的setOption方法部分。通过以下代码:

     this .options  =   {
      method:       
'post',
      asynchronous: 
true,
      contentType:  
'application/x-www-form-urlencoded',
      encoding:     
'UTF-8',
      parameters:   
''
    }


结合我们对ajax类的使用,我们可以看到,这部分是将我们在使用ajax类的参数部分加以读取和设置,我们为其加入两个参数,username和password,分别对应http basic认证的用户名和密码。修改后此部分代码如下:

  setOptions:  function (options)  {
    
this.options = {
      method:       
'post',
      asynchronous: 
true,
      contentType:  
'application/x-www-form-urlencoded',
      encoding:     
'UTF-8',
      parameters:   
''
      
/*begin plugin by hanguofeng-to add httpbasic*/
      username:        
'',
      password:        
''
      
/*end plugin by hanguofeng*/
    }
 这样修改后,我们在使用ajax类的相应方法时,只要在常规设置参数的地方加入username和password参数就可以了,例如:

 

  new  Ajax.Updater(
  
' myUpdateArea ' ,
  
' ajax.asp?type=selectCat_ ' + optype + ' &CatId= ' + lCatId,
  
{method:'get',username:'your-username',password:'your-password'}
 )


当然,仅有参数的设置还不行,我们还需要修改xmlhttp的open部分,以实现用户名和密码的发送。
回到我们的prototype.js,向下找到1042行,这部分实现了对网页的请求:

      this .transport.open( this .method.toUpperCase(),  this .url,
        
this .options.asynchronous);


这实际上是实现了xmlhttp对象的open方法,此对象除了我们常用的几个方法外,还有最后两个参数,我们对其进行修改:

       this .transport.open( this .options.method.toUpperCase(),  this .url,
        
this .options.asynchronous,  this .options.username,
        
this .options.password);

 

这样,就完成了对prototype的http basic认证的实现,还等什么,赶快试试吧。 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值