前端和后端交互的时候,前端的小伙伴都离不开 "请求" 。关于"请求"有几种方式来提供使用:Ajax、Axios、Fetch
那么Ajax、Axios、Fetch是什么呢?
1、Ajax
- Ajax是一个技术的统称,是一个概念模型,包括很多技术
- Ajax的特点:局部刷新页面,无需重载整个页面
- 注意:XMLHttpRequest并不等于是Ajax,XMLHttpRequest是实现Ajax的一种方式
-
//利用XMLHttpRequest实现Ajax,实现一个简单get请求 //缺点:此方法实现网络请求时,多个请求之间有先后关系会形成一个回调地狱 <body> <script> function ajax(url) { const xhr = new XMLHttpRequest(); xhr.open("get", url, false); xhr.onreadystatechange = function () { // 异步回调函数 if (xhr.readyState === 4) { if (xhr.status === 200) { console.info("响应结果", xhr.response) } } } xhr.send(null); } ajax('https://smallpig.site/api/category/getCategory') </script> </body>
2、Fetch
-
Fetch是一个API,是真实存在的,是基于promise的(ES6之后出现的Fetch)
-
Fetch特点:
-
使用promise,不使用回调函数(不形成回调地狱)
-
采用模块化设计,比如rep,res等对象分散
-
数据流对象处理数据,提高性能
-
-
//Fetach实现的简单请求 <body> <script> function ajaxFetch(url) { fetch(url).then(res => res.json()).then(data => { console.info(data) }) } ajaxFetch('https://smallpig.site/api/category/getCategory') </script> </body>
3、Axios
- Axios是一个基于promise封装的网络请求库,基于XHR进行二次封装(Axios是一个封装库)
- Axios的流程:
- 从浏览器中创建XMLHttpRequests
- 从node.js中创建http请求
- 支持promise API
- 拦截请求和响应
- 转换请求数据和响应数据
- 取消请求
- 自动转换 JSON 数据
- 客户端支持防御 XSRF
Ajax和Axios对比使用:
axios({
url:'/getUsers',
method:'get',
responseType:'json',
data:{
'a':1,
'b':2
}
}).then(function(response){
console.log(response);
console.log(response.data);
}).catch(function(error){
console.log(error);
})
$.ajax({
url:'/getUsers',
type:'get',
dataType:'json',
data:{
'a':1,
'b':2
},
success:function(response){
console.log(response);
}
})
待完善