自己写的简易ajax模型

来源:互联网 发布:淘宝卖家知道买家地址 编辑:程序博客网 时间:2024/04/29 18:58

/*
author zhangshuling
email  zhangshuling1214@126.com

*/
function  Ajax(){
    var _xmlHttp = null;
    this.createXMLHttpRequest = function(){
        try{
            if (window.ActiveXObject) {                                                       
                _xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");                                     
            }                                                                                 
            else if (window.XMLHttpRequest) {                                                     
                _xmlHttp = new XMLHttpRequest();                                               
            }
        }catch(e){
           alert(e.name +" : " + e.message);
        }
    }
   
    this.backFunction = function(_backFunction){
        if(_xmlHttp.readyState == 4) {
            if(_xmlHttp.status == 200) {
                _backFunction(_xmlHttp.responseXML);
            }
        }
         _xmlHttp.onreadystatechange = null;
    }

    this.doPost = function(_url,_parameter,_backFunction){
        try{
         _xmlHttp.open("POST",_url, false);
         _xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
         _xmlHttp.send(_parameter);
         }catch(e){
          alert(e.name +" : " + e.message);
        }
    }
   
    this.doGet = function(_url,_parameter,_backFunction){
       try{
           var _random = Math.round(Math.random()*10000);
           _xmlHttp.open("GET", (_url+"?random=" +_random +"&" + _parameter), false);
           _xmlHttp.send(null);
         }catch(e){
            alert(e.name +" : " + e.message);
         }
    }
   
    this.ajaxRequest = function(_url,_parameter,_method,_backFunction){
          try{
            this.createXMLHttpRequest();
            if(_method.toLowerCase() == "post"){
               this.doPost(_url,_parameter,_backFunction);
            }else{
               this.doGet(_url,_parameter,_backFunction); 
            }
            try{
              _xmlHttp.onreadystatechange = this.backFunction(_backFunction);
            }catch(err){
               //??????IE?????????????????
            }
         }catch(e){
            alert(e.name +" : " + e.message);
         }
     }

}

/*
 var url = "ajax.do";
 var parameter = "parameter=parameter";
 var method = "post"
 
 function callBack(xml){
  ....
 }
 
 new Ajax().ajaxRequest(url,parameter,method,callBack);

*/

原创粉丝点击