封裝ajax(相容IE)
阿新 • • 發佈:2019-02-15
//封裝適合各種情況的簡化版ajax函式 //利用解構,獲取將來引數物件中每個屬性值 //請求型別: "get"||"post" //請求的url地址: "xxx.php" //請求攜帶的引數: "變數1=值&..." //伺服器端返回值型別: "json"||"text" /*function ajax({type,url,data,dataType}){*/ function ajax(obj){ //伺服器端返回值型別預設為text dataType=obj.dataType||"text"; //只要遠端請求,必有延遲,只要延遲,比用promise等待完成後,才執行後續操作 return new Promise(function(resolve){//.then() //AJAX 4步/5步: if(XMLHttpRequest){ var xhr=new XMLHttpRequest();//1.獲得xhr物件 }else{ var xhr=new ActiveXObject("Microsoft.XMLHTTP"); } //如果是get請求,且傳入了data引數,才需要拼接url和data為get請求的完整地址 if(obj.type.toLowerCase()=="get"&&obj.data!==undefined) obj.url+="?"+obj.data; xhr.open(obj.type,obj.url,true);//2. 建立連線 //3. 設定請求狀態回撥函式 xhr.onreadystatechange=function(){ //如果請求完成,且成功! if(xhr.readyState==4&&xhr.status==200){ //如果伺服器端響應型別不是json,則呼叫後續resolve操作,並傳入原始responseText,做後續處理 if(obj.dataType.toLowerCase()!="json") resolve(xhr.responseText); else//如果伺服器端響應型別是json,則自動呼叫JSON.parse轉為js物件,再交給resolve函式做後續處理 resolve(JSON.parse(xhr.responseText)); } } //只有type為post,才需要設定請求頭 if(obj.type.toLowerCase()=="post") xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //只有type為post,才需要send時,傳入引數 xhr.send(obj.type.toLowerCase()=="post"?obj.data:null); }) }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <!-- <script src="https://cdn.polyfill.io/v2/polyfill.min.js"></script> --> <script src="js/polyfill.min.js"></script> <script src="js/ajax.js"></script> <script type="text/javascript"> ajax({ type:'get', url:'http://localhost/test/test.php', dataType:'json', }).then(function(data){ console.log(data); alert(data.ok); }) </script> </body> </html>
嘗試了下IE,IE9以及以上都可以用。不過需要先引入polyfill.min.js。
polyfill.min.js下載地址:http://www.bootcdn.cn/babel-polyfill/
開啟某個連結,直接複製貼上程式碼即可。