XMLHTTPRequest 的封装--Sender

本文介绍了一个跨浏览器兼容的AJAX实现方案,通过判断浏览器类型选择合适的XMLHttpRequest对象,并提供了发送请求的方法。同时,文章详细解释了如何处理响应及异常情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Function.registerNamespace("net.bingosoft.web");
net.bingosoft.web.Sender 
= function(){
 net.bingosoft.web.Sender.initializeBase(
this);
 
this.makeXMLHTTP = function() 
  
var xmlhttp = null;
  
if(window.ActiveXObject) {
   xmlhttp 
= new ActiveXObject("Microsoft.XMLHTTP");
  }
 else if(window.XMLHttpRequest) {
   xmlhttp 
= new XMLHttpRequest();
  }
 else {
   
throw new Error("Could not create xmlhttp on your browser");
  }
 
  
return xmlhttp;
 }

 
 
var _url;
 
var _method;
 
var _async;
 
var _callback;
 
var _sendbody;
 
 
var _xmlhttp   = null;
 
var _headerName   = "Content-Type";
 
var _headerValue  = "text/xml";
 
var _self    = this
 
 
this._onreadystatechange = function() {
  
if(_xmlhttp==nullreturn;
  
if(_xmlhttp.readyState != 4return;
  
if(_xmlhttp.status == 200 || _xmlhttp.status == 304{
   
if(_callback == null{
    
return;
   }
 else if(_callback instanceof Function) {
    
var retXmlDom = _xmlhttp.responseXML;
    
if(retXmlDom.xml==""{
     retXmlDom 
= new ActiveXObject("Microsoft.XMLDOM");
     retXmlDom.loadXML(_xmlhttp.responseText);
    }

    _callback.call(_self,retXmlDom);
   }
 else {
    _callback.call(_self, _xmlhttp.responseXML);
   }

   _xmlhttp 
= null;
  }
 else {
   
if(typeof(processException) != "undefined"{
    processException(_xmlhttp.status,_xmlhttp.statusText);
   }
 else {
    alert(_xmlhttp.status
+""+_xmlhttp.statusText);
   }

  }

 }

 
 
this.send = function(url,method,callback,sendBody) {
  _xmlhttp 
= this.makeXMLHTTP();
 
  _url   
=  url;
  _method  
=  method || "POST";
  _async  
= callback ? true : false;
  _callback 
=  callback || null;
  _sendbody  
=  sendBody || "";
  
  _xmlhttp.open(_method,_url,_async);
  _xmlhttp.setRequestHeader(_headerName,_headerValue);
  
if(_async) {
   _xmlhttp.onreadystatechange 
= function() {
    _self._onreadystatechange.call(_self);
   }

  }

  _xmlhttp.send(_sendbody);
  
if(!_async) {
   
var retXmlDom = _xmlhttp.responseXML;
   
if(retXmlDom.xml==""{
    retXmlDom 
= new ActiveXObject("Microsoft.XMLDOM");
    retXmlDom.loadXML(_xmlhttp.responseText);
   }
 
   
return retXmlDom;
  }

 }

}

net.bingosoft.web.Sender.registerClass(
"net.bingosoft.web.Sender"nullnull);
var $sender = new net.bingosoft.web.Sender();
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值