HTML与数据库交互的基本流程
HTML 本身无法直接调用数据库,需通过后端语言(如 PHP、Node.js、Python 等)作为中间层,实现以下流程:
VARCHAR
<input>
、<span>
INT
<input type="number">
DATE/TIMESTAMP
<input type="date">
BOOLEAN
<checkbox>
FLOAT/DOUBLE
<progress>
后端示例代码(以 Node.js + MySQL 为例)
后端查询数据库并返回数据
const express = require('express'); const mysql = require('mysql'); const app = express(); // 连接数据库 const db = mysql.createConnection({ host: 'localhost', user: 'root', password: 'password', database: 'test_db' }); // 获取用户信息接口 app.get('/api/users', (req, res) => { db.query('SELECT id, name, age, register_date FROM users', (err, results) => { if (err) throw err; res.json(results); // 返回数据给前端 }); }); app.listen(3000, () => console.log('Server running on port 3000'));
前端通过 AJAX 获取数据并渲染
<!DOCTYPE html> <html> <head>用户列表</title> </head> <body> <table id="userTable"> <thead> <tr> <th>ID</th> <th>姓名</th> <th>年龄</th> <th>注册日期</th> </tr> </thead> <tbody></tbody> </table> <script> fetch('/api/users') .then(response => response.json()) .then(data => { const tableBody = document.querySelector('#userTable tbody'); data.forEach(user => { const row = document.createElement('tr'); row.innerHTML = ` <td>${user.id}</td> <td>${user.name}</td> <td>${user.age}</td> <td>${new Date(user.register_date).toLocaleDateString()}</td> `; tableBody.appendChild(row); }); }); </script> </body> </html>
关键注意事项
-
数据类型转换:
- 后端需将数据库字段类型转换为前端可识别的格式(如
DATE
→YYYY-MM-DD
字符串)。 - 前端需处理特殊类型(如
Boolean
转为checked
属性)。
- 后端需将数据库字段类型转换为前端可识别的格式(如
-
安全性:
// 后端返回图片 URL
db.query('SELECT image_url FROM images WHERE id = ?', [id], (err, results) => {
res.json({ imageUrl: results[0].image_url });
});<img :src="user.imageUrl" alt="User Avatar">
- 前端通过表单或 AJAX 发送修改后的数据。
- 后端验证数据合法性,执行
UPDATE
语句。 - 返回操作结果(成功/失败)给前端。
示例:// 前端提交更新请求 fetch('/api/updateUser', { method: 'POST', body: JSON.stringify({ id, name, age }), headers: { 'Content-Type': 'application/json' } }) .then(response => response.json()) .then(data => alert(data.message));
// 后端处理更新 app.post('/api/updateUser', (req, res) => { const { id, name, age } = req.body; db.query('UPDATE users SET name = ?, age = ? WHERE id = ?', [name, age, id], (err, result) => { if (err) return res.status(500).json({ message: '更新失败' }); res.json({ message: '更新成功' }); });
问题 2:如果前端需要动态修改数据库数据(如更新表单),如何实现?
解答: