纯JS封装Ajax对象

封装好的对象:

 // JavaScript Document
var Ajax = function(sUrl, sMethod, oParam, fCallback){
 this.sUrl = sUrl;
 this.sMethod = sMethod;
 this.oParam = oParam;
 this.fCallback = fCallback;
 this.status = {
  1:'请求成功', 
  2:'http返回失败', 
  3:'数据加载中'
 }
 this.xmlHttp = null;
 //驱动函数
 this.Driver = function(){
  this.xmlHttp = this.CreateXmlHttp();
  this.xmlHttp.open(this.sMethod, this.sUrl, true); 
        this.xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
        this.xmlHttp.onreadystatechange = GetResult; //指定回调函数 
        this.xmlHttp.send(this.oParam); //发送请求 
 };
 //创建操作对象
 this.CreateXmlHttp = function(){
  var xmlHttp; 
        if (window.ActiveXObject) { //IE下 
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); 
        }
  if (window.XMLHttpRequest) { //其他浏览器如火狐 
            xmlHttp = new XMLHttpRequest(); 
        }
        return xmlHttp; 
 };
 //回调方法
 var GetResult = function(){
  if (this.readyState == 4) {//请求状态为4表示成功  
            if (this.status == 200) {//http状态200表示OK  
                eval(fCallback)(this.responseText);
            } else {//http返回状态失败  
                return this.status[2];
            } 
        } else {//请求状态还没有成功,页面等待  
            return this.status[3]; 
        } 
 };
}


调用方法:

new Ajax('test.php', 'get', {}, function(responseText){
	alert(responseText);
}).Driver();



 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值