AJAX 概念与 AXIOS 常规使用
如何使用 AJAX?
现代前端开发中,我们通常使用封装好的库如 axios 来简化 AJAX 请求。以下是基本使用步骤:
创建 XMLHttpRequest 对象(或使用 axios/Fetch)
配置请求方法和 URL
设置请求头(如果需要)
发送请求
处理响应数据
axios 的使用
axios 是一个基于 Promise 的 HTTP 客户端,用于浏览器和 node.js 环境。它比原生 AJAX 更简单易用,功能更强大。
安装 axios
直接在 HTML 中引入
<script src=”https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js”></script>
基本使用
// GET 请求
axios.get(‘/user?ID=12345’)
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
// POST 请求
axios.post(‘/user’, {
firstName: ‘John’,
lastName: ‘Doe’
})
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
认识 URL
什么是 URL?
URL(Uniform Resource Locator)即统一资源定位符,是互联网上标准资源的地址。
URL 的组成
一个完整的 URL 通常包括以下几个部分:
https://www.example.com:8080/path/to/resource?query=string#fragment
协议:https:// – 通信协议(HTTP/HTTPS/FTP 等)
域名:www.example.com – 服务器的地址
端口::8080 – 服务器端口(HTTP 默认 80,HTTPS 默认 443)
资源路径:/path/to/resource – 服务器上资源的路径
查询参数:?query=string – 发送给服务器的额外参数
片段标识:#fragment – 页面内的锚点位置
axios 查询参数
在 axios 中,可以通过 params 配置项添加查询参数:
axios.get(‘/user’, {
params: {
ID: 12345,
name: ‘John’
}
});
常用请求方法和数据提交
常用请求方法
- GET:请求指定的资源(查询)
- POST:向指定资源提交数据(创建)
- PUT:替换指定的资源(全量更新)
- PATCH:部分修改资源(部分更新)
- DELETE:删除指定资源
axios 请求配置
axios 请求可以配置多种选项:
axios({
method: ‘post’, // 请求方法
url: ‘/user/123’, // 请求地址
data: { // 请求体数据
firstName: ‘John’,
lastName: ‘Doe’
},
headers: { // 自定义请求头
‘X-Requested-With’: ‘XMLHttpRequest’
},
timeout: 1000, // 超时时间
params: { // URL 参数
ID: 12345
}
});
axios 错误处理
axios 提供了完善的错误处理机制:
axios.get(‘/user/12345’)
.then(response => {
console.log(response.data);
})
.catch(error => {
if (error.response) {
// 服务器返回了响应,但状态码不在 2xx 范围内
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// 请求已发出,但没有收到响应
console.log(error.request);
} else {
// 设置请求时发生错误
console.log(‘Error’, error.message);
}
console.log(error.config);
});
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 如遇到加密压缩包,请使用WINRAR解压,如遇到无法解压的请联系管理员!
7. 本站有不少源码未能详细测试(解密),不能分辨部分源码是病毒还是误报,所以没有进行任何修改,大家使用前请进行甄别!
66源码网 » AJAX 概念与 AXIOS 常规使用