有很多框架已經將 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)
}
})