Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
411 views
in Technique[技术] by (71.8m points)

javascript - Robust auto-refresh web page

I have many web pages that needs to auto-refresh once a minute. Easily done with META REFRESH or a some javascript. (And yes, the whole pages needs to refresh -- LOTS of content changing).

However, it needs to be as robust as possible. If the web server is momentarily down or there is a network hiccup, it can't refresh and will then get a 404 error, etc and be permanently stuck on the error page.

The only option I can come up with is host the whole page in an IFRAME, and have some script on the parent page fresh the framed page. The frame should be invisible so any resizing of the window would also need to resize the IFRAME.

Is there an easier, more elegant solution? (Going to Flash/AIR/Silverlight also isn't an option because of time constraints).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could load the new content of the page using Ajax. If your page is generated on the server side you can just omit the HTML around the body and only output it's content. You can then receive the new body with Ajax and replace the existing body of the page with body.innerHTML = request.responseText. In the Ajax callback you can do all kind of error handling you like, even ignore any error and retry the Ajax request.

<html>
<head>
<script type="text/javascript">
function doRequest() {
    var request = new XMLHttpRequest();
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            if (request.status == 200)
                 body.innerHTML = request.responseText;
            doRequest(); // restart the request
        }
    }
    request.open("get", "", true);
    request.send(null);
}
</script>
<body onload="doRequest()">
Page content...
</body>
</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...