AJAX Database 实例
AJAX Database 实例(中文讲解)
本教程展示如何使用 AJAX 与数据库(以 MongoDB 为例)交互,通过 Node.js 和 Express 构建后端,客户端使用 XMLHttpRequest
和 fetch
发送请求,实现动态查询和添加用户数据的功能。数据以 JSON 格式传输,结合 MongoDB 存储。本实例简洁实用,适合理解 AJAX 与数据库的交互。
1. 实例概述
- 目标:通过 AJAX 实现用户管理功能:
- GET 请求:查询 MongoDB 中的用户列表,显示在页面。
- POST 请求:提交新用户数据,存入 MongoDB。
- 技术栈:
- 客户端:HTML + JavaScript(
XMLHttpRequest
和fetch
)。 - 服务器:Node.js + Express。
- 数据库:MongoDB,存储 JSON 格式数据。
- 数据格式:JSON,用于前后端交互。
2. 环境准备
确保以下工具已安装:
- Node.js:LTS 版本(如 v20.x),运行
node -v
检查。 - MongoDB:本地运行或使用 MongoDB Atlas。
- npm 依赖:Express 和 MongoDB 驱动。
安装依赖:
mkdir ajax-database-example
cd ajax-database-example
npm init -y
npm install express mongodb
MongoDB 数据准备:
use myDatabase
db.users.insertMany([
{ name: "张三", age: 25, hobbies: ["读书", "旅行"] },
{ name: "李四", age: 30, hobbies: ["编程", "运动"] }
])
3. 服务器端代码(Node.js + Express + MongoDB)
创建 server.js
,实现与 MongoDB 的交互,返回 JSON 数据。
const express = require('express');
const { MongoClient } = require('mongodb');
const app = express();
const uri = 'mongodb://localhost:27017/myDatabase'; // 替换为你的 MongoDB 连接字符串
const client = new MongoClient(uri);
app.use(express.json());
app.use(express.static('public'));
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, POST');
next();
});
// 查询用户
app.get('/users', async (req, res) => {
try {
await client.connect();
const db = client.db('myDatabase');
const collection = db.collection('users');
const users = await collection.find({}).toArray();
res.json(users);
} catch (error) {
console.error('查询失败:', error);
res.status(500).json({ error: '服务器错误' });
} finally {
await client.close();
}
});
// 添加用户
app.post('/users', async (req, res) => {
try {
await client.connect();
const db = client.db('myDatabase');
const collection = db.collection('users');
const user = req.body;
if (!user.name || !user.age) {
return res.status(400).json({ error: '姓名和年龄必填' });
}
const result = await collection.insertOne(user);
res.json({ message: '添加成功', id: result.insertedId });
} catch (error) {
console.error('添加失败:', error);
res.status(500).json({ error: '服务器错误' });
} finally {
await client.close();
}
});
app.listen(3000, () => console.log('服务器运行在 http://localhost:3000'));
- 说明:
/users
(GET):查询 MongoDB 的users
集合,返回 JSON 数组。/users
(POST):接收 JSON 数据,插入新用户,返回成功消息。- CORS 允许跨域请求。
public
文件夹托管客户端 HTML。
4. 客户端代码(HTML + AJAX)
创建 public/index.html
,使用 XMLHttpRequest
和 fetch
与后端交互。
<!DOCTYPE html>
<html>
<head>
<title>AJAX 数据库示例</title>
<style>
pre { font-size: 16px; background: #f4f4f4; padding: 10px; }
button, input { padding: 10px; margin: 5px; }
table { border-collapse: collapse; margin-top: 10px; }
th, td { border: 1px solid #ccc; padding: 8px; text-align: left; }
</style>
</head>
<body>
<h1>用户管理</h1>
<div>
<input id="name" placeholder="姓名">
<input id="age" type="number" placeholder="年龄">
<button onclick="addUser()">添加用户(XMLHttpRequest)</button>
<button onclick="addUserFetch()">添加用户(Fetch)</button>
</div>
<button onclick="loadUsers()">加载用户</button>
<table id="userTable">
<thead>
<tr><th>姓名</th><th>年龄</th><th>爱好</th></tr>
</thead>
<tbody id="userList"></tbody>
</table>
<script>
// XMLHttpRequest 加载用户
function loadUsers() {
const xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost:3000/users', true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
try {
const users = JSON.parse(xhr.responseText);
displayUsers(users);
} catch (error) {
document.getElementById('userList').innerHTML = '<tr><td colspan="3">错误:JSON 解析失败</td></tr>';
}
} else {
document.getElementById('userList').innerHTML = `<tr><td colspan="3">错误:${xhr.statusText} (${xhr.status})</td></tr>`;
}
}
};
xhr.onerror = function () {
document.getElementById('userList').innerHTML = '<tr><td colspan="3">错误:网络错误</td></tr>';
};
xhr.send();
}
// XMLHttpRequest 添加用户
function addUser() {
const name = document.getElementById('name').value;
const age = parseInt(document.getElementById('age').value);
if (!name || !age) {
alert('请输入姓名和年龄');
return;
}
const xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost:3000/users', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
try {
const response = JSON.parse(xhr.responseText);
alert(response.message);
loadUsers();
} catch (error) {
alert('错误:JSON 解析失败');
}
} else {
alert(`添加失败:${xhr.statusText}`);
}
}
};
xhr.onerror = function () {
alert('网络错误');
};
xhr.send(JSON.stringify({ name, age, hobbies: ['未知'] }));
}
// Fetch 添加用户
async function addUserFetch() {
const name = document.getElementById('name').value;
const age = parseInt(document.getElementById('age').value);
if (!name || !age) {
alert('请输入姓名和年龄');
return;
}
try {
const response = await fetch('http://localhost:3000/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name, age, hobbies: ['未知'] })
});
if (!response.ok) throw new Error(`服务器错误:${response.status}`);
const result = await response.json();
alert(result.message);
loadUsers();
} catch (error) {
alert(`添加失败:${error.message}`);
}
}
// 显示用户列表
function displayUsers(users) {
const userList = document.getElementById('userList');
userList.innerHTML = '';
if (users.length === 0) {
userList.innerHTML = '<tr><td colspan="3">无用户数据</td></tr>';
return;
}
users.forEach(user => {
const row = document.createElement('tr');
row.innerHTML = `
<td>${user.name}</td>
<td>${user.age}</td>
<td>${user.hobbies ? user.hobbies.join(', ') : '无'}</td>
`;
userList.appendChild(row);
});
}
</script>
</body>
</html>
- 说明:
- 使用
<table>
显示用户数据,替代<pre>
,更直观。 loadUsers()
:通过 AJAX 获取用户列表,调用displayUsers()
渲染表格。addUser()
和addUserFetch()
:提交新用户数据,成功后刷新列表。- 处理 JSON 响应,解析错误提示用户。
5. 运行和测试
- 启动服务器:
node server.js
- 访问客户端:
- 打开浏览器,访问
http://localhost:3000
。 - 点击“加载用户”,显示用户表格:
姓名 年龄 爱好 张三 25 读书, 旅行 李四 30 编程, 运动
- 输入姓名和年龄,点击“添加用户(XMLHttpRequest)”或“添加用户(Fetch)”,添加用户并刷新表格。
- 响应示例:
- GET
/users
:json [ { "_id": "someObjectId1", "name": "张三", "age": 25, "hobbies": ["读书", "旅行"] }, { "_id": "someObjectId2", "name": "李四", "age": 30, "hobbies": ["编程", "运动"] } ]
- POST
/users
:json { "message": "添加成功", "id": "someObjectId3" }
6. JSON 在实例中的作用
- 客户端:
- 发送:POST 请求使用
JSON.stringify()
将数据转为 JSON 字符串。 - 接收:GET 响应通过
JSON.parse()
(XMLHttpRequest)或response.json()
(fetch)解析 JSON。 - 服务器:
- MongoDB 查询结果是 JavaScript 对象,
res.json()
转为 JSON 字符串。 - POST 请求接收 JSON 数据,存入 MongoDB。
- MongoDB:存储 JSON 格式文档,天然适合 AJAX 交互。
7. 注意事项与最佳实践
- 跨域处理:
- 本例使用 CORS(
Access-Control-Allow-Origin: *
)。 - 生产环境限制域名:
javascript res.header('Access-Control-Allow-Origin', 'http://trusted-domain.com');
- 错误处理:
XMLHttpRequest
:检查xhr.status
和onerror
。fetch
:检查response.ok
和try-catch
。- 服务器验证输入(如
name
和age
必填)。
- JSON 安全:
- 客户端:用
try-catch
包裹JSON.parse()
。 - 服务器:验证 POST 数据,防止注入。
- 超时设置:
XMLHttpRequest
:javascript xhr.timeout = 5000; xhr.ontimeout = () => alert('请求超时');
fetch
:javascript const controller = new AbortController(); setTimeout(() => controller.abort(), 5000); fetch('http://localhost:3000/users', { signal: controller.signal });
- 推荐 fetch:
fetch
语法简洁,基于 Promise,适合现代开发。XMLHttpRequest
适用于进度监控(如文件上传)。
- 性能优化:
- MongoDB 查询使用索引:
javascript db.users.createIndex({ name: 1 });
- 分页查询:
javascript const users = await collection.find({}).skip(0).limit(10).toArray();
- 调试:
- 使用浏览器开发者工具(Network 面板)检查请求和响应。
- 使用
JSON.stringify(data, null, 2)
格式化输出。
8. 总结
- 实例功能:通过 AJAX(
XMLHttpRequest
和fetch
)查询和添加 MongoDB 用户,渲染为表格。 - 数据库交互:Node.js + MongoDB 处理查询和插入,返回 JSON。
- JSON 角色:前后端交互核心,
JSON.stringify()
和JSON.parse()
关键。 - 最佳实践:处理跨域、错误、超时,优先使用
fetch
,优化数据库查询。
如果你需要其他数据库(如 MySQL、PostgreSQL)、更复杂功能(如搜索、删除、分页),或想深入某部分,请告诉我,我会提供详细代码或指导!
const express = require('express');
const { MongoClient } = require('mongodb');
const app = express();
const uri = 'mongodb://localhost:27017/myDatabase';
const client = new MongoClient(uri);
app.use(express.json());
app.use(express.static('public'));
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, POST');
next();
});
app.get('/users', async (req, res) => {
try {
await client.connect();
const db = client.db('myDatabase');
const collection = db.collection('users');
const users = await collection.find({}).toArray();
res.json(users);
} catch (error) {
console.error('查询失败:', error);
res.status(500).json({ error: '服务器错误' });
} finally {
await client.close();
}
});
app.post('/users', async (req, res) => {
try {
await client.connect();
const db = client.db('myDatabase');
const collection = db.collection('users');
const user = req.body;
if (!user.name || !user.age) {
return res.status(400).json({ error: '姓名和年龄必填' });
}
const result = await collection.insertOne(user);
res.json({ message: '添加成功', id: result.insertedId });
} catch (error) {
console.error('添加失败:', error);
res.status(500).json({ error: '服务器错误' });
} finally {
await client.close();
}
});
app.listen(3000, () => console.log('服务器运行在 http://localhost:3000'));
<!DOCTYPE html>
<html>
<head>
<title>AJAX 数据库示例</title>
<style>
pre { font-size: 16px; background: #f4f4f4; padding: 10px; }
button, input { padding: 10px; margin: 5px; }
table { border-collapse: collapse; margin-top: 10px; }
th, td { border: 1px solid #ccc; padding: 8px; text-align: left; }
</style>
</head>
<body>
<h1>用户管理</h1>
<div>
<input id="name" placeholder="姓名">
<input id="age" type="number" placeholder="年龄">
<button onclick="addUser()">添加用户(XMLHttpRequest)</button>
<button onclick="addUserFetch()">添加用户(Fetch)</button>
</div>
<button onclick="loadUsers()">加载用户</button>
<table id="userTable">
<thead>
<tr><th>姓名</th><th>年龄</th><th>爱好</th></tr>
</thead>
<tbody id="userList"></tbody>
</table>
<script>
function loadUsers() {
const xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost:3000/users', true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
try {
const users = JSON.parse(xhr.responseText);
displayUsers(users);
} catch (error) {
document.getElementById('userList').innerHTML = '<tr><td colspan="3">错误:JSON 解析失败</td></tr>';
}
} else {
document.getElementById('userList').innerHTML = `<tr><td colspan="3">错误:${xhr.statusText} (${xhr.status})</td></tr>`;
}
}
};
xhr.onerror = function () {
document.getElementById('userList').innerHTML = '<tr><td colspan="3">错误:网络错误</td></tr>';
};
xhr.send();
}
function addUser() {
const name = document.getElementById('name').value;
const age = parseInt(document.getElementById('age').value);
if (!name || !age) {
alert('请输入姓名和年龄');
return;
}
const xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost:3000/users', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
try {
const response = JSON.parse(xhr.responseText);
alert(response.message);
loadUsers();
} catch (error) {
alert('错误:JSON 解析失败');
}
} else {
alert(`添加失败:${xhr.statusText}`);
}
}
};
xhr.onerror = function () {
alert('网络错误');
};
xhr.send(JSON.stringify({ name, age, hobbies: ['未知'] }));
}
async function addUserFetch() {
const name = document.getElementById('name').value;
const age = parseInt(document.getElementById('age').value);
if (!name || !age) {
alert('请输入姓名和年龄');
return;
}
try {
const response = await fetch('http://localhost:3000/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name, age, hobbies: ['未知'] })
});
if (!response.ok) throw new Error(`服务器错误:${response.status}`);
const result = await response.json();
alert(result.message);
loadUsers();
} catch (error) {
alert(`添加失败:${error.message}`);
}
}
function displayUsers(users) {
const userList = document.getElementById('userList');
userList.innerHTML = '';
if (users.length === 0) {
userList.innerHTML = '<tr><td colspan="3">无用户数据</td></tr>';
return;
}
users.forEach(user => {
const row = document.createElement('tr');
row.innerHTML = `
<td>${user.name}</td>
<td>${user.age}</td>
<td>${user.hobbies ? user.hobbies.join(', ') : '无'}</td>
`;
userList.appendChild(row);
});
}
</script>
</body>
</html>