Ajax
- [什么是 Ajax](#什么是 Ajax)
- [Ajax 的核心原理](#Ajax 的核心原理)
- [Ajax 工作流程详解](#Ajax 工作流程详解)
- [原生 Ajax 实现(不重要)](#原生 Ajax 实现(不重要))
-
- [GET 请求示例](#GET 请求示例)
- [POST 请求示例](#POST 请求示例)
- [jQuery Ajax 实战](#jQuery Ajax 实战)
- [Ajax 进阶技巧](#Ajax 进阶技巧)
-
- 错误处理
- [同步 vs 异步](#同步 vs 异步)
什么是 Ajax
Ajax(Asynchronous JavaScript and XML)是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。它允许网页与服务器进行异步数据交换,提升用户体验。
Ajax 的核心原理
浏览器事件触发
创建 XMLHttpRequest 对象
配置请求参数
发送请求到服务器
服务器处理请求
服务器返回响应数据
回调函数处理数据
局部更新页面 DOM
Ajax 工作流程详解
基本请求流程
服务器 浏览器 用户 服务器 浏览器 用户 点击按钮/触发事件 创建 XMLHttpRequest 发送异步请求 处理请求逻辑 返回 JSON/XML 数据 解析响应数据 局部更新页面内容
请求状态变化
Ajax 请求有 5 种状态(readyState):
| 状态值 | 状态描述 | 说明 |
|---|---|---|
| 0 | UNSENT | 请求未初始化 |
| 1 | OPENED | 已建立服务器连接 |
| 2 | HEADERS_RECEIVED | 已接收响应头 |
| 3 | LOADING | 正在下载响应体 |
| 4 | DONE | 请求完成 |
原生 Ajax 实现(不重要)
GET 请求示例
javascript
// 创建 XMLHttpRequest 对象
var xhr = new XMLHttpRequest();
// 配置请求
xhr.open('GET', '/api/users?id=1', true);
// 设置响应类型
xhr.responseType = 'json';
// 监听状态变化
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) { // 请求完成
if (xhr.status === 200) {
console.log('请求成功:', xhr.response);
} else {
console.error('请求失败:', xhr.status);
}
}
};
// 发送请求
xhr.send();
POST 请求示例
javascript
var xhr = new XMLHttpRequest();
xhr.open('POST', '/api/users', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var result = JSON.parse(xhr.responseText);
console.log('创建成功:', result);
}
};
var data = {
name: '张三',
age: 25,
email: 'zhangsan@example.com'
};
xhr.send(JSON.stringify(data));
jQuery Ajax 实战
jQuery 封装了 Ajax 操作,让异步请求更加简洁。
基本语法
jQuery 的 $.ajax() 方法是最核心的 Ajax 操作函数,下面详细介绍它的常用配置项和使用方式。
常用配置项
| 配置项 | 类型 | 说明 | 默认值 |
|---|---|---|---|
type |
String | 请求方式:"get" 或 "post" |
"get" |
url |
String | 请求的服务器地址 | 当前页面地址 |
data |
Object/String | 发送到服务器的数据 | 无 |
dataType |
String | 预期服务器返回的数据类型:"json"、"xml"、"text" 等 |
自动推断 |
success |
Function | 请求成功时的回调函数 | 无 |
error |
Function | 请求失败时的回调函数 | 无 |
complete |
Function | 请求完成(无论成功失败)时的回调函数 | 无 |
async |
Boolean | 是否异步请求 | true |
timeout |
Number | 请求超时时间(毫秒) | 无 |
GET 请求示例
javascript
$.ajax({
type: "get", // 请求方式
url: "/api/users", // 请求地址
data: { id: 1, name: "张三" }, // 请求参数(自动转为 URL 查询字符串)
dataType: "json", // 预期返回 JSON 数据
success: function(response) { // 成功回调
console.log("请求成功:", response);
},
error: function(xhr, status) { // 失败回调
console.error("请求失败:", status);
}
});
上面的请求最终会发送到
/api/users?id=1&name=张三
POST 请求示例
javascript
$.ajax({
type: "post", // 请求方式
url: "/api/users", // 请求地址
data: { // 请求参数(自动转为请求体)
name: "张三",
age: 25,
email: "zhangsan@example.com"
},
dataType: "json",
success: function(response) {
console.log("创建成功:", response);
},
error: function(xhr, status) {
console.error("创建失败:", status);
}
});
简化写法
jQuery 还提供了更简洁的快捷方法:
javascript
// GET 请求简化写法
$.get("/api/users", { id: 1 }, function(response) {
console.log("GET 请求成功:", response);
}, "json");
// POST 请求简化写法
$.post("/api/users", { name: "张三" }, function(response) {
console.log("POST 请求成功:", response);
}, "json");
// 加载 HTML 片段
$("#result").load("/api/notice.html");
请求流程
成功
失败
调用 $.ajax
配置参数
拼接请求地址和参数
创建 XMLHttpRequest
发送请求到服务器
请求结果
调用 success 回调
调用 error 回调
调用 complete 回调
请求结束
分页查询实战
下面是一个简化的图书分页查询示例
javascript
// 1. 发送 Ajax 请求获取图书数据
$.ajax({
type: "get",
url: "/book/getListByPage?currentPage=1",
success: function (result) {
// 2. 检查是否登录
if (result.code == "UNLOGIN") {
alert("请先登录");
location.href = "login.html";
return;
}
// 3. 获取图书列表
var books = result.data.records;
// 4. 遍历数据,生成表格 HTML
var html = "";
for (var book of books) {
html += "<tr>";
html += "<td>" + book.id + "</td>";
html += "<td>" + book.bookName + "</td>";
html += "<td>" + book.author + "</td>";
html += "<td>" + book.price + "</td>";
html += "<td><a href='edit.html?bookId=" + book.id + "'>修改</a></td>";
html += "</tr>";
}
// 5. 更新页面表格
$("tbody").html(html);
},
error: function(error) {
if (error.status == 401) {
alert("登录已过期,请重新登录");
location.href = "login.html";
}
}
});
| 步骤 | 作用 |
|---|---|
| ① 发送请求 | 向服务器请求第 1 页的图书数据 |
| ② 登录检查 | 未登录则跳转到登录页 |
| ③ 获取数据 | 从返回结果中提取图书列表 |
| ④ 拼接 HTML | 把每条图书数据转为表格行 |
| ⑤ 更新页面 | 把生成的 HTML 填入表格 |
分页请求流程
未登录
已登录
页面加载
请求第1页数据
登录状态?
跳转登录页
获取图书列表
拼接表格HTML
更新页面显示
用户点击页码
请求对应页码数据
Ajax 进阶技巧
错误处理
javascript
$.ajax({
url: "/api/data",
success: function(response) {
// 处理成功响应
},
error: function(xhr, status, error) {
switch(xhr.status) {
case 401:
// 未授权,跳转登录
location.href = "/login";
break;
case 403:
alert("没有权限访问");
break;
case 404:
alert("请求的资源不存在");
break;
case 500:
alert("服务器内部错误");
break;
default:
alert("请求失败: " + error);
}
},
complete: function() {
// 无论成功失败都会执行
console.log("请求完成");
}
});
同步 vs 异步
同步请求
用户操作
发送请求
页面卡住
等待响应
更新页面
异步请求
用户操作
发送请求
页面可继续操作
后台等待响应
回调更新页面