原生xhr、jquery ajax、axios、fetch对比
// 原生XHRvar xhr = new XMLHttpRequest();xhr.open('GET', url);xhr.onreadystatechange = function() {if (xhr.readyState === 4 && xhr.status === 200) {console.log(xhr.responseText) // 从服务器获取数据}}xhr.send()//jquery ajax$.ajax({type: 'POST',url: url,data: data,dataType: dataType,success: function() {},error: function() {}})//axiosaxios({method:'get',url:url,}).then(function(response) {}.catch(function(error)));// fetchfetch(url).then(response => {if (response.ok) {return response.json();}}).then(data => console.log(data)).catch(err => console.log(err))
我们一眼就能看出fetch和axios很像,他们的API是基于Promise设计的,经过优化后,代码会更加优雅
try {const response = await fetch(url)const data = await response.json()console.log(data);} catch (error) {console.log('请求出错', error);}
他是浏览器底层的api,不需要引入库就能使用。
Post请求
不过他并不完善,很多情况下需要我们再次封装。
// jquery ajax$.post(url, {name: 'test'})// fetchfetch(url, {method: 'POST',body: Object.keys({name: 'test'}).map((key) => {return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);}).join('&')})
由于fetch是比较底层的API,所以需要我们手动将参数拼接成’name=test’的格式,而jquery ajax已经封装好了。所以fetch并不是开箱即用的。
另外,fetch还不支持超时控制。
带Cookie发送请求
如果我们想要在异步请求中带上cookie参数,那么需要显式指定credentials参数:
fetch(url, {credentials: 'include'})
