AJAX 概念与 axios 使用
什么是 AJAX?
AJAX(Asynchronous JavaScript and XML)即异步的 JavaScript 和 XML,是一种创建快速动态网页的技术。通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新,这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
核心原理:AJAX 通过浏览器内置的 XMLHttpRequest
对象(或 Fetch API)向服务器发送异步请求,获取数据后利用 JavaScript 操作 DOM 更新页面内容。这种技术改变了传统的同步请求方式,大大提升了用户体验。
如何使用 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);});
HTTP 协议-报文
请求报文
格式:
请求行(方法 URL 协议版本)
请求头(多个键值对)
空行
请求体(可选)
示例:
POST /login HTTP/1.1
Host: example.com
Content-Type: application/json
Content-Length: 42{"username":"admin","password":"123456"}
响应报文
格式:
状态行(协议版本 状态码 状态描述)
响应头(多个键值对)
空行
响应体(可选)
示例:
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 30{"status":"success","data":{}}
HTTP 响应状态码
- 1xx:信息性状态码(请求已被接收,继续处理)
- 2xx:成功状态码(请求已成功处理)
- 200 OK
- 201 Created
- 204 No Content
- 3xx:重定向状态码(需要进一步操作)
- 301 Moved Permanently
- 302 Found
- 304 Not Modified
- 4xx:客户端错误状态码(请求有语法错误或无法实现)
- 400 Bad Request
- 401 Unauthorized
- 403 Forbidden
- 404 Not Found
- 5xx:服务器错误状态码(服务器未能实现合法请求)
- 500 Internal Server Error
- 502 Bad Gateway
- 503 Service Unavailable
接口文档
接口文档是前后端协作的重要依据,通常包含:
- 接口地址
- 请求方法
- 请求参数(类型、是否必需、描述)
- 响应数据格式
- 可能的错误码
form-serialize 插件
form-serialize 是一个方便的表单序列化工具,可以将表单数据转换为对象或查询字符串。
使用示例:
const form = document.querySelector('form');
const data = serialize(form, { hash: true }); // 返回对象
// 或
const queryString = serialize(form); // 返回查询字符串
与 axios 结合使用:
document.querySelector('form').addEventListener('submit', function(e) {e.preventDefault();const data = serialize(this, { hash: true });axios.post('/api/submit', data).then(response => {console.log(response.data);});
});