Home > Article > Web Front-end > HTML-encapsulating native Ajax
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!