axios和ajax及fetch原理淺析
這三個其實都是用來請求數據的,那他們的區別在哪里呢?其實 axios 和 ajax
都是對XMLHttpRequest這個對象的封裝;而fetch則是window下的一個方法,是一個更底層的方法。
ajax
其實重點就是首先實例一個XMLHttpRequest對象,用其中的open方法建立連接;send方法傳輸數據(前端傳到后台);然后再利用onreadystatechange 監聽readyState的變化,當其為4時,代表請求完成;簡單的代碼實現如下:
const Ajax={
get: function(url, fn) {
// XMLHttpRequest對象用於在后台與服務器交換數據
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onreadystatechange = function() {
// readyState 為4說明請求已完成
if (xhr.readyState == 4 && xhr.status == 200) {
// 從服務器獲得數據
fn.call(this, xhr.responseText);
}
};
xhr.send();
},
// datat應為'a=a1&b=b1'這種字符串格式,在jq里如果data為對象會自動將對象轉成這種字符串格式
post: function (url, data, fn) {
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
// 添加http頭,發送信息至服務器時內容編碼類型
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && (xhr.status == 200)) {
fn.call(this, xhr.responseText);
}
};
xhr.send(data);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
axios
axios其實就是在ajax的基礎上加了promise,具體如下:
const myAxios = {
get: function(url) {
return new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
resolve(xhr.responseText)
}
};
xhr.send();
})
},
1
2
3
4
5
6
7
8
9
10
11
12
13
14
fetch
fetch的使用這里就不多做贅述,有很多這方面的文檔。fetch首先不想ajax一樣需要引入jq;如果想自己實現ajax呢,步驟相對於fetch來說也是相當的繁瑣;同時fetch也加入了promise,解決了回調地獄的問題;使用fetch雖然簡單,但是也有一些問題需要注意:
cookie傳遞
必須在header參數里面加上credientials: ‘include’,才會如xhr一樣將當前cookies帶到請求中去
fetch和xhr的不同
fetch雖然底層,但是還是缺少一些常用xhr有的方法,比如能夠取消請求(abort)方法
fetch在服務器返回4xx、5xx時是不會拋出錯誤的,這里需要手動通過,通過response中的ok字段和status字段來判斷
————————————————
版權聲明:本文為CSDN博主「qq_39096319」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/qq_39096319/article/details/82347033