要实现页面实时刷新数据库,通常会涉及到以下几个基础概念和技术:
function pollData() {
fetch('/api/data')
.then(response => response.json())
.then(data => {
// 更新页面内容
document.getElementById('data').innerText = JSON.stringify(data);
// 设置下一次轮询
setTimeout(pollData, 5000); // 每5秒轮询一次
})
.catch(error => console.error('Error:', error));
}
// 开始轮询
pollData();
const socket = new WebSocket('ws://example.com/socket');
socket.onmessage = function(event) {
const data = JSON.parse(event.data);
// 更新页面内容
document.getElementById('data').innerText = JSON.stringify(data);
};
socket.onerror = function(error) {
console.error('WebSocket Error:', error);
};
const eventSource = new EventSource('/api/sse');
eventSource.onmessage = function(event) {
const data = JSON.parse(event.data);
// 更新页面内容
document.getElementById('data').innerText = JSON.stringify(data);
};
eventSource.onerror = function(error) {
console.error('SSE Error:', error);
};
选择合适的技术取决于具体的应用场景和对实时性的要求。在实际开发中,可能需要结合多种技术以达到最佳效果。
领取专属 10元无门槛券
手把手带您无忧上云