Skip to content

AJAX 数据库

异步 JavaScript 的一个常见用例是从服务器获取数据,而服务器又从数据库检索信息。这允许在不重新加载整个页面的情况下动态显示数据库内容。

本节概述了其概念:客户端的 JavaScript 发起请求,服务器端代码处理数据库交互并返回数据(通常是 JSON)。

注意: 我们在此不展示详细的数据库连接或查询代码,因为它们因数据库(SQL、NoSQL)和服务器端语言/框架(Node.js、PHP、Python 等)的不同而差异很大。重点在于异步的客户端-服务器流程。

想象一个客户姓名下拉列表。当用户选择一个客户时,我们想从服务器/数据库获取他们的详细信息(例如 ID、地址、联系方式)并将其显示在页面上。

<label for="customerSelect">Select a Customer:</label>
<select id="customerSelect" name="customer">
<option value="">-- Select --</option>
<!-- 选项通常也通过动态方式填充 -->
<option value="ALFKI">Alfreds Futterkiste</option>
<option value="NORTS">North/South</option>
<option value="WOLZA">Wolski Zajazd</option>
</select>
<div id="customerDetails" style="margin-top: 15px; border: 1px solid #eee; padding: 10px; min-height: 50px;">
<p>Customer details will be listed here...</p>
</div>
const customerSelect = document.getElementById('customerSelect');
const detailsDiv = document.getElementById('customerDetails');
async function showCustomer(customerId) {
// 如果没有选择客户(例如,默认的 '-- Select --' 选项)
if (!customerId) {
detailsDiv.innerHTML = '<p>Please select a customer.</p>';
return;
}
detailsDiv.innerHTML = '<p><i>Fetching details...</i></p>';
try {
// 向服务器端点发起请求,传递客户 ID
const response = await fetch(`/api/customers/${encodeURIComponent(customerId)}`);
// 示例端点:/api/customers/ALFKI
if (!response.ok) {
// 处理潜在错误,例如 ID 无效时的 404 Not Found
// 如果服务器提供了错误消息,则获取它
const errorText = await response.text();
throw new Error(`Failed to fetch customer (${response.status}): ${errorText || response.statusText}`);
}
// 期望服务器返回 JSON 格式的客户详细信息
const customerData = await response.json();
// 显示获取的数据(假设结构简单)
// 这里进行基本的数据清理很重要!
const name = customerData.name ? String(customerData.name).replace(/</g, "&lt;") : 'N/A';
const contact = customerData.contact ? String(customerData.contact).replace(/</g, "&lt;") : 'N/A';
const city = customerData.city ? String(customerData.city).replace(/</g, "&lt;") : 'N/A';
detailsDiv.innerHTML =
`<h3>${name}</h3>
<p>**联系方式:** ${contact}</p>
<p>**城市:** ${city}</p>`;
} catch (error) {
console.error('Error fetching customer details:', error);
detailsDiv.innerHTML = `<p style="color: red;">加载详情时出错: ${error.message}</p>`;
}
}
// 为选择下拉列表添加事件监听器
customerSelect.addEventListener('change', (event) => {
const selectedCustomerId = event.target.value;
showCustomer(selectedCustomerId);
});
  • 事件监听器: <select> 元素上的 change 事件监听器在用户选择不同选项时触发。
  • showCustomer 函数: 将选定的 customerId 作为输入。
  • 输入检查: 处理选择了默认空选项的情况。
  • Fetch 请求: 向动态服务器端点(例如 /api/customers/CUSTOMER_ID)发送 GET 请求。特定的客户 ID 包含在 URL 路径中。
  • 错误处理: 检查 response.ok 并使用 try...catch 处理网络或服务器错误。如果状态码不是 OK,它会尝试从响应体中读取错误消息。
  • JSON 解析: 假定服务器响应的是表示客户详细信息的 JSON 数据。
  • DOM 更新: 解析 JSON 并使用这些信息更新 customerDetails div。应用了基本的 HTML 数据清理,以防止 XSS 漏洞。

服务器端代码(位于 /api/customers/:id 端点)负责:

  1. 接收请求: 解析 URL 以提取 customerId。
  2. 输入验证/清理: 确保接收到的 ID 是有效的且在数据库查询中安全可用。
  3. 数据库查询: 连接到数据库并执行查询(例如使用提供的 ID 执行 SELECT name, contact, city FROM customers WHERE customer_id = ?)。
  4. 处理结果: 检查是否找到了客户。
  5. 格式化响应: 如果找到,将客户数据格式化为 JSON 对象(例如 {"name": "Alfreds Futterkiste", "contact": "Maria Anders", "city": "Berlin"}).
  6. 发送响应: 将 JSON 数据连同适当的 Content-Type: application/json 头部和 200 OK 状态码发送回客户端。
  7. 错误响应: 如果未找到客户,则发送 404 Not Found 状态码。如果发生数据库错误,则发送 500 Internal Server Error 状态码,可能在响应体中包含错误消息(纯文本或 JSON 格式)。

具体的实现细节(数据库驱动、ORM、错误处理策略)很大程度上取决于所选的后端技术。

关键原则是关注点分离(separation of concerns):客户端处理用户界面并发起请求,而服务器管理数据访问、业务逻辑,并为客户端准备数据。