前端 | Ajax&Axios模块
warning:
这篇文章距离上次修改已过249天,其中的内容可能已经有所变动。
Ajax和Axios都是前端用于发送HTTP请求的工具,但它们有一些区别:
- 创建XMLHttpRequest对象发送异步请求的传统方式称为Ajax。
- Axios是一个基于Promise的HTTP客户端,用于浏览器和node.js,它能够在node.js环境中使用并发送http请求,并在浏览器中使用XMLHttpRequest。
Ajax的使用示例:
var xhr = new XMLHttpRequest();
xhr.open("GET", "url", true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
}
};
xhr.send();
Axios的使用示例:
axios.get('url')
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
Axios的优点:
- 在浏览器中发送XMLHttpRequest请求,在node.js中发送http请求。
- 支持Promise API。
- 能够拦截请求和响应。
- 能够转换请求和响应数据。
- 客户端支持跨域请求。
总结:Axios是基于Promise的HTTP客户端,它比Ajax更现代,功能更强大,使用也更方便。
评论已关闭