ajax,fetch,axios的区别及运用
AJAX
- 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。
- 通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
- 传统的网页(不使用 AJAX)如果需要更新内容,必需重载整个网页面。
1. ajax的封装(创建myajax.js 文件夹)
/** * { * method:get, * url: '/login.do', * content: 'username=admin&password=123' * success: functon(e){ * * } * } * * * * @param {*} json */
function myajax(json) {
// 1. 获取 XmlHttpRequest
var xhr = getXHR();
// 2. 打开连接发送请求
xhr.open(json.method, json.url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // 请求头部
xhr.send(json.content);
// 3. 处理响应
xhr.onreadystatechange = function (e) {
// 根据就绪码判断响应是否完成
if (e.target.readyState === 4) {
// 根据状态码判断成功失败
if (e.target.status === 200) {
/* console.log(e.target.responseText); alert('响应内容是 :' + e.target.responseText); */
json.success(e.target.responseText);
}
}
}
}
function getXHR() {
if (window.XMLHttpRequest) {
return new window.XMLHttpRequest;
} else {
// 兼容IE浏览器低版本
new window.AtiveXObject("Microsoft.XMLHTTP");
}
}
export default myajax; //暴露出去
2.调用myajax
myajax({
method: "post", //请求方式post get
url: "http://127.0.0.1:8089/api/login", //请求地址
content: `username=${ username}&password=${ password}`, //请求正文
success: function(e) { //成功的函数回调
const data = JSON.parse(e);
if (data.resultcode === -1) { //接口文档中给的参数,判断是否等于-1
//登录失败
that.message = data.resultinfo;
} else {
//登录成功
that.$router.replace({ path: "/main" });
}
}
});
Fetch
- fetch号称是AJAX的替代品,是在ES6出现的,使用了ES6中的promise对象。Fetch是基于promise设计的。Fetch的代码结构比起ajax简单多了,参数有点像jQuery ajax。但是,一定记住fetch不是ajax的进一步封装,而是原生js,没有使用XMLHttpRequest对象。
- -优势
- 语法简洁,更加语义化
- 基于标准 Promise 实现,支持 async/await
- 同构方便,使用 isomorphic-fetch
- 更加底层,提供的API丰富(request, response)
- 脱离了XHR
fetch使用代码
---get请求---
// 通过fetch获取百度的错误提示页面
fetch('https://www.baidu.com/search/error.html', {
method: 'GET'
})
.then((res)=>{
return res.text() // res.json();
})
.then((res)=>{
console.log(res)
})
---post请求---
// 通过fetch获取百度的错误提示页面
fetch('https://www.baidu.com/search/error.html', {
method: 'POST',
body: new URLSearchParams([["foo", 1],["bar", 2]]).toString() // 这里是请求对象
})
.then((res)=>{
return res.text()
})
.then((res)=>{
console.log(res)
})
Axios
-axios主要是jQuery的ajax与fetch的融合,十分强大
- 特点
- 支持浏览器和node.js
- 支持promise(重点)
- 能拦截请求和响应
- 能转换请求和响应数据
- 能取消请求
- 自动转换JSON数据
- 浏览器端支持防止CSRF(跨站请求伪造)
1. 安装
npm install axios //然后在需要的地方调用
2. 安装
axios({
method: 'post', //请求方式
url: '/user/12345', //请求地址
data: { //请求数据
firstName: 'Fred',
lastName: 'Flintstone'
}
}).then(res=>{
console.log(`成功的回调${ res}`)
}).catch(err=>{
console.log(`错误的回调${ err}`)
});
还没有评论,来说两句吧...