原生js封装ajax 案例
有时候在做开发的时候,会用到js但是做的页面却不能引用jQuery,担心会和别的jQuery版本冲突。所以就自己封装一个原生的ajax来使用 。
functionajax(options){options=options||{};options.type=(options.type||"GET").toUpperCase();options.dataType=options.dataType||"json";varparams=formatParams(options.data);//创建-非IE6-第一步if(window.XMLHttpRequest){varxhr=newXMLHttpRequest();}else{//IE6及其以下版本浏览器varxhr=newActiveXObject('Microsoft.XMLHTTP');}//接收-第三步xhr.onreadystatechange=function(){if(xhr.readyState==4){varstatus=xhr.status;if(status>=200&&status<300){options.success&&options.success(xhr.responseText,xhr.responseXML);}else{options.fail&&options.fail(status);}}}//连接和发送-第二步if(options.type=="GET"){xhr.open("GET",options.url+"?"+params,true);xhr.send(null);}elseif(options.type=="POST"){xhr.open("POST",options.url,true);//设置表单提交时的内容类型xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");xhr.send(params);//==============================}}//格式化参数functionformatParams(data){vararr=[];for(varnameindata){arr.push(encodeURIComponent(name)+"="+encodeURIComponent(data[name]));}arr.push(("v="+Math.random()).replace(".",""));returnarr.join("&");}
在js里使用的调用
functionfindService(){ajax({url:"xxxxxxx",//请求地址type:"POST",//请求方式dataType:"json",//数据格式success:function(response){vararray=eval(response);//执行成功的代码},fail:function(status){//执行失败的代码}});}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。