Home  >  Article  >  Web Front-end  >  HTML-encapsulating native Ajax

HTML-encapsulating native Ajax

巴扎黑
巴扎黑Original
2017-06-27 09:14:501477browse
function ajax(data){    //data{data:"",dataType:"xml/json",type:"get/post",url:"",asyn:"true/false",success:funtion(){},failure:function(){}}
    //datapost={username:123,pwd=456}
    //dataGet="username=123&pwd=456"
    //第一步:创建XHR对象var xhr=null;
    if(window.XMLHttpRequest){//标准的浏览器  xhr=new XMLHttpRequest();  
    }else{
      xhr=new ActiveXObject('Microsoft.XMLHTTP');
    }//第二步:准备发送前的一些配置参数var type=data.type=='get'?'get':'post';
    var url='';
    if(data.url){
        url=data.url;
        if(type=='get'){
            url+="?"+data.data+'&_t='+new Date().getTime();//(就是dataGet)}
    }
    var flag=data.asyn=='true'?'true':'false';
    xhr.open(type,url,flag);//第三步:执行发送的动作if(type=='get("Content-Type","application/x-www-form-urlencoded")
        xhr.send(data.data);//就是dataPost}//第四步:指定回调函数xhr.onreadstatechange=function(){
       if(this.readyState==4){
            if(this.status==200){
                 if(typeof data.success=='function'){
                     var d=data.dataType=='xml'?this.responseXML:this.responseText;
                     data.success(d);
                }
            }else{
                  if(typeof data.failure=='function'){
                       data.failure();
                  }
            }
        }
    }
}

 

The above is the detailed content of HTML-encapsulating native Ajax. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn