JavaScript定时获取数据库数据涉及几个基础概念和技术点:
setTimeout
和setInterval
函数来执行定时任务。以下是一个使用Node.js和Express结合AJAX定时获取数据库数据的简单示例:
const express = require('express');
const app = express();
const mysql = require('mysql');
// 创建数据库连接
const db = mysql.createConnection({
host: 'localhost',
user: 'your_username',
password: 'your_password',
database: 'your_database'
});
db.connect((err) => {
if (err) throw err;
console.log('Database connected!');
});
app.get('/data', (req, res) => {
const sql = 'SELECT * FROM your_table';
db.query(sql, (err, result) => {
if (err) throw err;
res.send(result);
});
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>定时获取数据</title>
</head>
<body>
<div id="data"></div>
<script>
function fetchData() {
fetch('http://localhost:3000/data')
.then(response => response.json())
.then(data => {
document.getElementById('data').innerHTML = JSON.stringify(data);
})
.catch(error => console.error('Error:', error));
}
// 每5秒获取一次数据
setInterval(fetchData, 5000);
</script>
</body>
</html>
通过以上方法,可以有效实现JavaScript定时获取数据库数据,并解决常见的问题。
没有搜到相关的文章