ajax
- ajax是一种创建交互式网页应用的网页开发技术,是一种在无需重新加载整个网页的情况下,更够更新部分网页的技术,通过在后台与服务器进行少量数据交换,Ajax可以使网页实现异步更新
- 优点:
- 可以在不重新加载整个网页的情况下,对网页的某部分进行更新
- 缺点:
- 本身是针对MVC编程,不符合前端MVVM的浪潮
- 基于原生XHR开发,XHR本身的架构不清晰
- 不符合关注分离的原则
- 配置和调用方式非常混乱,而且基于事件的异步模型不友好
- 使用示例
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "ajax_info.txt", true);
//xhttp.open("GET", "index.html", true);
//xhttp.open("GET", "demo_get.asp?t=" + Math.random(), true);
//xhttp.open("POST", "demo_post.asp", true);
//async=true 当服务器准备响应时将执行onreadystatechange函数
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
//使用responseText属性得到服务器响应的字符串数据,使用responseXML属性得到服务器响应的XML数据
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.send();
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
fetch
- 在ES6中出现,使用了ES6中的promise对象,fetch是基于Promise设计的,代码结构ajax简单很多,注意fetch不是ajax的进一步封装,而是原生js,没有使用XMLHttpRequest对象
- 优点:
- 语法简洁,更加语义化
- 基于标准Promise实现,支持async/await
- 更加底层,提供的API丰富(request,response)
- 脱离了XHR,是ES规范里新的实现方式
- 缺点:
- 只对网络请求报错,对400,500都当作成功的请求,服务器返回400,500时并不会reject,只有网络错误导致这些请求不能完成时,fetch才会reject
- 不支持abort,不支持超时控制,使用setTimeout以及Promise.reject的实现的超时控制并不能阻止请求过程继续在后台运行,会造成流量的浪费
- 没有办法原生检测请求的进度,但是XHR可以
- 使用示例
const user = { name: 'John', surname: 'Smith' };
const response = await fetch('/article/fetch/post/user', {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify(user)
});
axios
- Axios 是一种基于 Promise 封装的 HTTP 客户端
- 特点
- 浏览器端发起 XMLHttpRequests 请求
- node 端发起 http 请求
- 支持 Promise API
- 监听请求和返回
- 对请求和返回进行转化
- 取消请求
- 自动转换 json 数据
- 客户端支持抵御 XSRF 攻击
- 使用实例
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
// 在发送请求之前做些什么
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
// 2xx 范围内的状态码都会触发该函数。
// 对响应数据做点什么
return response;
}, function (error) {
// 超出 2xx 范围的状态码都会触发该函数。
// 对响应错误做点什么
return Promise.reject(error);
});
//取消拦截器
const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
-------------------------------------------------------------------------------------2024.5.10每日一题