Bootstrap 是一个流行的前端框架,用于快速开发响应式和移动优先的网页。Bootstrap 表格是 Bootstrap 中的一个组件,用于展示数据表格。将 Bootstrap 表格与数据库结合使用,可以实现动态的数据展示。
原因:
解决方法:
假设我们使用 Node.js 和 Express 作为后端,MySQL 作为数据库,Bootstrap 作为前端框架。
后端代码:
const express = require('express');
const mysql = require('mysql');
const app = express();
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'mydatabase'
});
connection.connect();
app.get('/api/data', (req, res) => {
const sql = 'SELECT * FROM mytable';
connection.query(sql, (err, results) => {
if (err) throw err;
res.json(results);
});
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
前端代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bootstrap Table</title>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody id="table-body">
</tbody>
</table>
</div>
<script>
fetch('http://localhost:3000/api/data')
.then(response => response.json())
.then(data => {
const tableBody = document.getElementById('table-body');
data.forEach(item => {
const row = document.createElement('tr');
row.innerHTML = `
<td>${item.id}</td>
<td>${item.name}</td>
<td>${item.email}</td>
`;
tableBody.appendChild(row);
});
});
</script>
</body>
</html>
通过以上步骤,你可以实现一个简单的 Bootstrap 表格加载数据库数据的功能。如果遇到具体问题,可以根据错误信息进一步排查和解决。