DIV定时切换正常但内容不自动刷新,求JavaScript解决方法
问题描述
我是JavaScript新手,正在学习相关技术。办公室中有两台监控网络(文件数量、文件可用性等)的服务器,两台服务器每分钟都会生成一个仪表盘页面。我希望在电视上展示这两个仪表盘,每隔2分钟切换一次,并且无需刷新整个网页即可更新仪表盘内容。
目前已实现两个仪表盘按预期间隔切换,但两个DIV中的内容无法自动更新/刷新,仅在网页打开时加载数据,之后不再更新。
以下是我的代码:
HTML代码
<!DOCTYPE html> <html> <head> <title>Live Update</title> <meta charset="UTF-8"> <link rel="stylesheet" type="text/css" href="style.css"> <script type="text/javascript" src="autoUpdateVTS.js"></script> <script type="text/javascript" src="autoUpdateIDS.js"></script> <script type="text/javascript" src="script.js"></script> </head> <body> <div id="VTS"> </div> <div id="IDS" class="hide"> </div> </body> </html>
CSS代码
html, body { } #VTS { } #IDS { } .hide { display: none !important; }
autoUpdateVTS.js代码
document.addEventListener("DOMContentLoaded", function() { var xhr = null; getXmlHttpRequestObject = function() { if(!xhr) { xhr = new XMLHttpRequest(); } return xhr; }; updateVTS = function() { var now = new Date(); var url = 'http://vtc130/hm01/dashboard.htm'; + now.getTime(); xhr = getXmlHttpRequestObject(); xhr.onreadystatechange = evenHandlervts; // asynchronous requests xhr.open("GET", url, true); xhr.send(null); }; updateVTS(); function evenHandlervts() { // Check response is ready or not if(xhr.readyState == 4 && xhr.status == 200) { dataDiv = document.getElementById('VTS'); // Set current data text dataDiv.innerHTML = xhr.responseText; // Update the live data every 20 sec setTimeout(updateVTS, 20000); } } });
script.js代码
window.addEventListener('load', function() { switchVTSIDS = function() { setInterval(function() { VTS.classList.toggle("hide"); IDS.classList.toggle("hide"); }, 120000); }; switchVTSIDS(); });
解决思路
1. 修复URL缓存问题
你在拼接URL时多了一个分号,导致时间戳没有被添加到URL末尾,浏览器会缓存旧的仪表盘页面,后续请求都返回缓存内容,看起来没更新:
// 错误写法 var url = 'http://vtc130/hm01/dashboard.htm'; + now.getTime();
修复为:
// 正确写法,添加?让时间戳作为查询参数,避免URL格式错误 var url = 'http://vtc130/hm01/dashboard.htm?' + now.getTime();
2. 确保定时器稳定触发
当前只在请求成功时才设置下一次定时器,如果某次请求失败(比如服务器临时不可达),后续更新会停止。应该把定时器移到请求发送前,不管请求成功失败都继续定时:
修改updateVTS函数:
updateVTS = function() { var now = new Date(); var url = 'http://vtc130/hm01/dashboard.htm?' + now.getTime(); xhr = getXmlHttpRequestObject(); xhr.onreadystatechange = evenHandlervts; xhr.open("GET", url, true); xhr.send(null); // 不管请求结果如何,20秒后再次执行 setTimeout(updateVTS, 20000); };
同时移除evenHandlervts里的setTimeout(updateVTS, 20000);
3. 避免全局变量冲突
你的getXmlHttpRequestObject、updateVTS等函数没有用var/let/const声明,会变成全局变量,可能和其他脚本冲突。建议用局部变量包裹:
document.addEventListener("DOMContentLoaded", function() { let xhr = null; const getXmlHttpRequestObject = function() { if(!xhr) { xhr = new XMLHttpRequest(); } return xhr; }; const updateVTS = function() { // ... 原有代码 }; updateVTS(); function evenHandlervts() { // ... 原有代码 } });
4. 修复元素获取问题
在script.js中,直接使用VTS和IDS变量在严格模式下会报错,应该通过document.getElementById获取元素:
window.addEventListener('load', function() { const VTS = document.getElementById('VTS'); const IDS = document.getElementById('IDS'); const switchVTSIDS = function() { setInterval(function() { VTS.classList.toggle("hide"); IDS.classList.toggle("hide"); }, 120000); }; switchVTSIDS(); });
5. 可选:用Fetch API替代XMLHttpRequest
作为新手,Fetch API比XMLHttpRequest更简洁易读,推荐尝试:
document.addEventListener("DOMContentLoaded", function() { const updateVTS = async function() { try { const now = new Date(); const url = 'http://vtc130/hm01/dashboard.htm?' + now.getTime(); const response = await fetch(url); if(response.ok) { const html = await response.text(); document.getElementById('VTS').innerHTML = html; } } catch(err) { console.error('更新VTS仪表盘失败:', err); } finally { setTimeout(updateVTS, 20000); } }; updateVTS(); });
把这些修复应用到autoUpdateVTS.js和autoUpdateIDS.js中,仪表盘应该就能自动更新了。
内容的提问来源于stack exchange,提问作者Robert van Ierland
相关产品推荐
相关产品推荐

