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

来源:互联网 发布:网络软文兼职 编辑:程序博客网 时间:2024/05/22 08:12

问题:想要显示来自一个文件的条目,但是该文件会经常更新
解决方案:使用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>

这里写图片描述