您的位置:首页 > 其它

使用定时器以新数据自动更新页面

2017-08-23 13:10 281 查看
问题:想要显示来自一个文件的条目,但是该文件会经常更新

解决方案:使用Ajax和一个定时器来周期性地检查文件,获取更新显示。

<!DOCTYPE html>
<html>
<head>
<title>On Demand Select</title>
</head>
<body>
<ul id="update"></ul>
<script>
var xmlHttp;
function populateList() {
if(!xmlHttp){
xmlHttp = new XMLHttpRequest();
}
var url = "http://localhost/text.txt?name=aaa";
xmlHttp.open("GET",url,true);
xmlHttp.onreadystatechange = processResponse;
xmlHttp.send(null);
}
function processResponse(){
if(xmlHttp.readyState ==4 && xmlHttp.status==200){
var li = document.createElement("li");
var txt = document.createTextNode(xmlHttp.responseText);
li.appendChild(txt);
document.getElementById("update").appendChild(li);
setTimeout(processResponse,15000);
}else if(xmlHttp.readyState == 4 && xmlHttp.status != 200){
alert(xmlHttp.responseText);
}
}
window.onload = function(){
xmlHttp = new XMLHttpRequest();
populateList();
}
</script>
</body>
</html>



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐