1 <script> 2 // 封裝通用的xhr物件,兼容各個版本 3 function creatXHR() { 4 // 判斷瀏覽器是否將XMLHttpRequest作為本地物件實作,針對IE7,firefox, opera等 5 if (typeof XMLHttpRequest != "undefined") { 6 return new XMLHttpRequest(); 7 } 8 else if (typeof ActiveXObject != "undefined") { 9 // 將所有可能出現的ActiveXObject版本放在一個陣列中 10 var xhrArr = [ 11 'Microsoft.XMLHTTP', 12 'MSXML2.XMLHTTP.6.0', 13 'MSXML2.XMLHTTP.5.0', 14 'MSXML2.XMLHTTP.4.0', 15 'MSXML2.XMLHTTP.3.0', 16 'MSXML2.XMLHTTP.2.0' 17 ]; 18 // 遍歷創建XMLHttpRequest物件 19 var xhr; 20 for (let i = 0; i < array.length; i++) { 21 try { 22 // 創建XMLHrrpRequest物件 23 xhr = new ActiveXObject(xhrArr[i]); 24 break; 25 } catch (error) { 26 27 } 28 29 } 30 return xhr; 31 } 32 else{ 33 throw new Error('不支持XMLHttpRequest物件'); 34 } 35 } 36 // 創建xhr 37 var xhr = creatXHR(); 38 // 存盤獲取到的資料 39 var data; 40 41 // 回應XMLHttpRequest物件狀態變化的函式,onreadystatechange在readyState屬性發生改變時觸發 42 xhr.onreadystatechange = function (/* callback */) { 43 // 異步呼叫成功,回應內容決議完成,可以在客戶端呼叫 44 if (xhr.readyState == 4) { 45 // 200 OK,304 讀取快取 46 if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) { 47 // 獲取服務器回傳的資料 48 // 資料以字串型別存放在 xhr.responseText 49 // json序列化決議xhr.responseText 50 // 將ajax獲取到的資料傳遞出去 51 data =https://www.cnblogs.com/walker-cheng/p/ JSON.parse(xhr.responseText); 52 // 或者在引數中傳入callback,在此處執行回呼函式 53 // callback && callback(); 54 } 55 } 56 }; 57 58 59 // 創建請求,這里只是創建,并不發送 60 xhr.open("get", "./xxx.json", true); 61 62 // 發送請求 63 xhr.send(null); 64 65 /* 使用post方法,傳參方式 66 // 創建請求,這里只是創建,并不發送 67 xhr.open("post", "./xxx.json", true); 68 // 設定http頭部資訊 69 xhr.setRequestHeader("Content-type", "application/x-www-form-urlcoded"); 70 xhr.send({param1:'strrr', param2:789}); 71 */ 72 </script>
想不起來Ajax實作,就來看看,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/102421.html
標籤:JavaScript
上一篇:前端通過ajax獲取base64轉blob下載PDF方法
下一篇:Vue使用rem做自適應布局
