上一篇
html加载数据库数据
- 行业动态
- 2025-05-12
- 7
后端连接数据库查询数据,嵌入HTML展示
环境准备
- 安装Node.js:用于运行服务器端代码。
- 安装MySQL:作为数据库管理系统。
- 创建项目目录:包含服务器端代码(如
server.js
)和HTML文件(如index.html
)。
数据库操作
创建数据库和表
CREATE DATABASE test_db; USE test_db; CREATE TABLE users (id INT PRIMARY KEY, name VARCHAR(50), age INT); INSERT INTO users VALUES (1, 'Alice', 25), (2, 'Bob', 30);
服务器端连接数据库
使用mysql
模块(需安装npm install mysql
):const mysql = require('mysql'); const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: 'your_password', database: 'test_db' }); connection.connect();
查询数据并发送至前端
app.get('/api/users', (req, res) => { connection.query('SELECT FROM users', (error, results) => { if (error) throw error; res.json(results); // 将数据以JSON格式返回 }); });
前端加载数据
通过API获取数据
使用fetch
从前端请求数据:fetch('/api/users') .then(response => response.json()) .then(data => { // 处理数据(如插入HTML表格) });
动态渲染HTML
示例:将用户数据插入表格:<table id="userTable"> <tr><th>ID</th><th>Name</th><th>Age</th></tr> </table> <script> fetch('/api/users') .then(response => response.json()) .then(users => { const table = document.getElementById('userTable'); users.forEach(user => { const row = table.insertRow(); row.insertCell().textContent = user.id; row.insertCell().textContent = user.name; row.insertCell().textContent = user.age; }); }); </script>
技术对比表
步骤 | 传统PHP方式 | Node.js + API方式 |
---|---|---|
数据库连接 | 使用mysqli_connect | 使用mysql 模块 |
数据传递 | 混合HTML和PHP代码 | 通过REST API返回JSON |
前端处理 | 依赖服务器渲染 | 前端独立请求和处理数据 |
适用场景 | 小型项目、快速开发 | 前后端分离、复杂交互 |
相关问题与解答
问题1:如何将数据库换成MongoDB?
解答:
- 安装
mongodb
模块(npm install mongodb
)。 - 修改连接代码:
const { MongoClient } = require('mongodb'); const client = new MongoClient('mongodb://localhost:27017'); client.connect().then(() => { const db = client.db('test_db'); db.collection('users').find().toArray((err, results) => { if (err) throw err; res.json(results); }); });
- 调整前端代码(逻辑不变,仅数据结构可能不同)。
问题2:如何实现数据的实时更新?
解答:
- WebSocket:建立长连接,服务器主动推送数据更新。
- 轮询(Polling):前端定时发送请求检查数据变化。
- 数据库触发器:监听数据变更并通知前端(需结合消息队列或Socket)。
示例(轮询):setInterval(() => { fetch('/api/users').then(response => response.json()).then(updateTable); }, 5000); // 每5秒