Javascript 使用ajax刷新页面是一种不好的做法吗?
我有一个仪表板,我需要使其动态,以便用户有最新的数据 我的第一个“懒惰”想法是使用ajax调用同一个页面,然后每5秒只更新一些节点元素。以下是一个例子:Javascript 使用ajax刷新页面是一种不好的做法吗?,javascript,Javascript,我有一个仪表板,我需要使其动态,以便用户有最新的数据 我的第一个“懒惰”想法是使用ajax调用同一个页面,然后每5秒只更新一些节点元素。以下是一个例子: const interval = setInterval(function() { updateData(); }, 5000); function updateData(){ let xmlhttp; xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatech
const interval = setInterval(function() {
updateData();
}, 5000);
function updateData(){
let xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200){
let parser = new DOMParser();
let responseHtml = parser.parseFromString(xmlhttp.responseText, 'text/html');
// Find div in the response
let responseData = responseHtml.querySelector(".card-highlight .card-body");
// Find the same div in the current page and get HTML data
let currentData = document.querySelector(".card-highlight .card-body").innerHTML;
// Check if the content is not the same
if (responseData && currentData !== responseData.innerHTML) {
// Update div with new data
document.querySelector(".card-highlight .card-body").innerHTML = data.innerHTML
}
}
}
xmlhttp.open("GET", window.location.href, true);
xmlhttp.send();
}
这是一个本地仪表板,因此与外部服务器之间没有延迟。我正在刷新页面。这对于我的案例来说非常好,因为我不需要额外的代码,而且我可以在多个页面上完成,而不需要更改后端
每个人都使用特定的端点来返回准备好的数据。但是,当我们只需要刷新时是否有必要
这很简单,对我来说很有效,但是,这是一个坏习惯还是一个坏主意
- 资源使用
- 保安