有很多框架已經將 ajax 封裝,需要的時候只需要調用就好,比如 jquery 是最常用的。我們為什么還需要學習 ajax 的封裝呢?首先加強我們對ajax的認識,其次如果只是因為ajax請求需要引入框架,我們可以自己封裝一個,這樣就不需要引入多余的框架了。
一、封裝的注意點
封裝是為了把相同的部分都實現公用,節省資源,提高代碼復用性,工作效率也高,所以需要把不同的參數事件類型等通過調用的時候傳入,需要注意點有:
1.1、傳參
發送 ajax 請求時,主要參數有:
- 請求url
- 請求類型
- 請求參數
- 成功回調
- 失敗回調
- 超時時間
以上六個參數必須設置成動態傳入的,便於控制任意 ajax 請求。超時時間可以統一設置,如果作為傳參可以更方便地控制任意一個請求超時。
1.2、請求類型分別處理
請求類型有 get 和 post 兩種,get類型傳值的時候,數據跟在url地址后,post傳值時在請求體內攜帶,還需設置請求數據類型。所以需要判斷分別處理。
if(type == 'GET'){ xhr.open( 'GET' , url+'?'+strData , true ) shr.send() }else{ xhr.open('POST',url,true) xhr.setRequestHeader('content-type','application/x-www-form-urlencoded') xhr.send( strData ) }
1.3、請求超時處理
網絡服務異常或者接口異常的時候,請求發送出去沒有響應,頁面也不會做出任何反應,需要全局加一個超時處理,超出時間還沒有返回時,自動結束請求,返回異常。
使用語法如下:
//設置時間為2s xhr.timeout = 2000 ; //超時回調 xhr.ontimeout = function(){ console.log('網絡異常,稍后重試') }
1.4、錯誤處理
網絡中斷,請求無法發送到服務器時,需要對請求失敗進行處理。使用onerror事件處理。
使用語法如下:
xhr.onerror = function(){ console.log("網絡異常,請檢查網絡") }
二、封裝 ajax 代碼
根據ajax的請求流程,封裝代碼如下:便於以后使用,建議收藏。
function ajax(option) { // method, url, data, timeout, success, error var xhr; var str = data2str(option.data); if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); }else { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } if (option.type.toLowerCase() === 'post') { xhr.open(option.type, option.url, true); xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhr.send(str); } else if (option.type.toLowerCase() === 'get') { xhr.open(option.type, option.url + '?' + str, true); xhr.send(); } xhr.onreadystatechange = function () { if (xhr.readyState === 4) { clearTimeout(timer); if (xhr.status >= 200 && xhr.status < 300 || xhr === 304) { option.success(xhr); }else { option.error(xhr); } } }; if (option.timeout) { var timer = setTimeout(function () { xhr.abort(); clearTimeout(timer); }, option.timeout) } } // 將對象轉化成用於傳輸的字符串 function data2str(data) { var res = []; data.t = new Date().getTime(); for (var key in data) { res.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key])); } return res.join('&'); }
使用的時候調用代碼如下:
ajax({ method:'GET', url:'1.txt', data:{ //請求數據 }, timeout:2000, success:(res)=>{ console.log('成功返回',res.response) }, error: err => { console.log('錯誤信息',err) } })