在JavaScript中读取数据库数据通常涉及到以下几个步骤:
fetch
或axios
等库从API获取数据。const express = require('express');
const mysql = require('mysql');
const app = express();
const port = 3000;
// 创建数据库连接
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'testdb'
});
connection.connect();
// 创建API路由
app.get('/data', (req, res) => {
connection.query('SELECT * FROM users', (error, results, fields) => {
if (error) throw error;
res.json(results);
});
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Fetch Data</title>
</head>
<body>
<div id="data"></div>
<script>
fetch('http://localhost:3000/data')
.then(response => response.json())
.then(data => {
const dataDiv = document.getElementById('data');
data.forEach(user => {
const userDiv = document.createElement('div');
userDiv.textContent = `ID: ${user.id}, Name: ${user.name}`;
dataDiv.appendChild(userDiv);
});
})
.catch(error => console.error('Error:', error));
</script>
</body>
</html>
通过上述步骤,你可以使用JavaScript读取数据库数据。关键在于设置正确的服务器端API,并使用前端JavaScript通过API获取数据。根据具体需求,可以选择不同的数据库和框架。