本章节分享一段代码,它是对原生的ajax的封装,因为在默认状态下具有一定的兼容性问题,所有良好的封装还是非常有必要的,希望下面的代码能够给需要的朋友带来帮助,代码如下:
   [ 其他 ] 运行代码    下载代码
<script>
function Ajax(url,data){
  this.url=url;
  this.data=data;
  this.browser=(function(){  
    if(navigator.userAgent.indexOf("MSIE")>0){  
      return "MSIE";//IE浏览器
    }
        else{
      return "other";//其他
    }
  })()
}
Ajax.prototype={
  get:function(){
    var result;
    var xmlhttp;
    if(this.browser=='MSIE'){
      try{
        xmlhttp=new ActiveXObject('microsoft.xmlhttp');
      }
          catch(e){
        xmlhttp=new ActiveXObject('msxml2.xmlhttp');
      }
    }
        else{
      xmlhttp=new XMLHttpRequest();
    };
    xmlhttp.onreadystatechange=function(){
      result = xmlhttp.responseText;//闭包,不能采用this.属性
    };
    xmlhttp.open('GET',this.url+'?'+this.data,false);//true无法抓取数据,why?
    mlhttp.send(null);
    return result;
  },
  post:function(){
    var result;
    var xmlhttp;
    if(this.browser=='MSIE'){
      xmlhttp=new ActiveXObject('microsoft.xmlhttp');
    }
        else{
      xmlhttp=new XMLHttpRequest();
    };
    xmlhttp.onreadystatechange=function(){
      result = xmlhttp.responseText;//闭包,不能采用this.属性
    };
    xmlhttp.open('POST',this.url,false);//需设为false,否则无法抓取responseText
    xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");//POST中,这句必须
    xmlhttp.send(this.data);
    return result;
  }
};
  
  
window.onload=function(){
  document.getElementById("btn").onclick=function(){
    var p=document.getElementById("t").value;
    var a=new Ajax("phpOOP/getPage.php","page="+p);
    document.getElementById("box").innerHTML=a.get();
  }
}
</script>

代码描述:javascript对ajax封装。javascript对ajax封装代码实例



100 134



用户评论
大牛,别默默的看了,快登录帮我点评一下吧!:)      登录 | 注册



×
×
51前端

注册

×
绑定手机

请绑定手机号,在继续操作

×
单次下载支付

应付金额:279

支付完成后,回到下载页面,在进行下载

官方QQ群
意见反馈
qq群

扫描上面二维码加微信群

官方QQ群

jQuery/js讨论群
群号:642649996
Css3+Html5讨论群
群号:322131262

加群请备注:从官网了解到