Ajax 与 Axios 入门实战:异步数据交互与 JSON 综合应用
1. Ajax 与 Axios 基础
Ajax(Asynchronous JavaScript and XML)允许网页在不重新加载整个页面的情况下,与服务器进行数据交换。其核心优势在于:
- 局部刷新:仅更新页面中的部分内容,提升用户体验。
- 异步请求:浏览器发送请求后,无需等待服务器响应即可继续执行其他操作。
Axios 是一个基于 Promise 的 HTTP 客户端,可以更简洁地发送 Ajax 请求。它支持浏览器和 Node.js,并提供了丰富的配置项。
1.1 Axios GET 请求示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Axios GET 请求</title>
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/axios@0.18.0/dist/axios.min.js"></script>
<script>
// 发送 GET 请求,参数拼接在 URL 中
axios.get("http://localhost:8080/userServlet?name=张三&age=25")
.then(response => {
// 请求成功时处理响应数据
console.log(response);
console.log(response.data); // 获取服务器返回的数据
})
.catch(error => {
// 请求失败时处理错误信息
console.error("请求失败:", error);
})
.finally(() => {
// 无论成功与否都会执行
console.log("请求结束");
});
</script>
</body>
</html>
代码解析:
axios.get(url):向指定 URL 发送 GET 请求,参数通过?key=value形式附加。.then(response => { ... }):响应成功后执行的回调,response.data包含服务器返回的数据。.catch(error => { ... }):处理请求过程中的异常。.finally(() => { ... }):无论请求成功或失败,都会执行的清理操作。
1.2 Axios POST 请求示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Axios POST 请求</title>
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/axios@0.18.0/dist/axios.min.js"></script>
<script>
// 发送 POST 请求,参数通过第二个参数传递
axios.post("http://localhost:8080/loginServlet", "username=李四&password=abc123")
.then(response => {
console.log("服务器响应数据:", response.data);
})
.catch(error => {
console.error("请求出错:", error);
})
.finally(() => {
console.log("请求已完成");
});
</script>
</body>
</html>
代码解析:
axios.post(url, data):第一个参数是请求地址,第二个参数是要发送的数据(字符串格式如key=value&key2=value2)。- 其余链式调用部分与 GET 请求相同。
2. 实战:异步校验用户名是否已存在
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>用户名校验</title>
<style>
.available { color: green; }
.taken { color: red; }
</style>
</head>
<body>
<form>
<input type="text" id="usernameInput" placeholder="请输入用户名">
<span id="statusMsg"></span><br>
<input type="password" placeholder="密码"><br>
<button>提交</button>
</form>
<script src="https://cdn.jsdelivr.net/npm/axios@0.18.0/dist/axios.min.js"></script>
<script>
/*
后台接口说明:
- URL: "http://localhost:8080/checkUser"
- 参数名: username(值来自输入框)
- 响应:如果用户名存在则返回 false,否则返回 true
- 假设已有用户:"张三"
*/
document.getElementById("usernameInput").onblur = function() {
let inputName = this.value.trim();
// 若输入为空,则不做处理
if (!inputName) return;
axios.get("http://localhost:8080/checkUser?username=" + encodeURIComponent(inputName))
.then(res => {
let msgSpan = document.getElementById("statusMsg");
if (res.data) {
// 用户名可用
msgSpan.textContent = "✓ 用户名可用";
msgSpan.className = "available";
} else {
// 用户名已存在
msgSpan.textContent = "✗ 该用户名已被占用";
msgSpan.className = "taken";
}
})
.catch(err => {
console.error("校验失败:", err);
});
};
</script>
</body>
</html>
- 核心逻辑:监听输入框的失焦事件(
onblur),利用 Axios 发送 GET 请求到后台验证用户名。 - 根据服务器返回的布尔值(
true/false),动态更新提示消息的文本和颜色。
3. Ajax 与 JSON 综合实战:动态加载好友列表
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>好友列表</title>
<style>
table { border-collapse: collapse; width: 500px; }
th, td { border: 1px solid #ccc; padding: 8px; text-align: center; }
</style>
</head>
<body>
<h2>好友管理</h2>
<button onclick="loadFriends()">加载好友列表</button>
<hr>
<div id="infoBox"></div>
<table id="friendTable">
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>年龄</th>
</tr>
</thead>
<tbody id="tableBody">
<!-- 动态数据将渲染到这里 -->
</tbody>
</table>
<script src="https://cdn.jsdelivr.net/npm/axios@0.18.0/dist/axios.min.js"></script>
<script>
/*
后台接口:
- URL: "http://localhost:8080/friendList"
- 响应 JSON 格式: { "success": true, "message": "查询成功", "data": [{"id": "001", "name": "王五", "age": 22}, ...] }
*/
function loadFriends() {
axios.get("http://localhost:8080/friendList")
.then(resp => {
let result = resp.data; // 解析 JSON 对象
let infoDiv = document.getElementById("infoBox");
let body = document.getElementById("tableBody");
if (result.success) {
infoDiv.textContent = result.message; // "查询成功"
let rowsHtml = "";
// 遍历好友数组
result.data.forEach(friend => {
rowsHtml += `<tr><td>${friend.id}</td><td>${friend.name}</td><td>${friend.age}</td></tr>`;
});
body.innerHTML = rowsHtml;
} else {
infoDiv.textContent = "数据加载失败";
}
})
.catch(error => {
console.error("请求异常:", error);
});
}
</script>
</body>
</html>
- 点击按钮触发
loadFriends()函数,通过 GET 请求获取好友数据。 - 服务器返回 JSON 对象,其中包含标志位(
success)、消息体(message)和实际数据数组(data)。 - 使用 ES6 模板字符串和
forEach循环将数据动态渲染到表格中。