如果我要一整页每N秒刷新,我会把这样的事情在HTML: meta http-equiv="refresh" content="5"
如何每N秒安排一次ajax呼叫?
有没有做这样的事情了AJAX调用一个标准的做法?我希望安排一个AJAX调用,每隔10秒就会关闭一次,以便更新页面的各个部分,而无需刷新整个页面。如果我可以在不同的时间安排多个AJAX调用会更好,因为页面的某些部分可能需要比其他部分更频繁地更新。
TIA
如果我要一整页每N秒刷新,我会把这样的事情在HTML: meta http-equiv="refresh" content="5"
如何每N秒安排一次ajax呼叫?
有没有做这样的事情了AJAX调用一个标准的做法?我希望安排一个AJAX调用,每隔10秒就会关闭一次,以便更新页面的各个部分,而无需刷新整个页面。如果我可以在不同的时间安排多个AJAX调用会更好,因为页面的某些部分可能需要比其他部分更频繁地更新。
TIA
你可以使用setTimeout
或setInterval
(后者可能是最适合你想要做什么)。
setInterval(makeRequest, (10 * 1000));
...其中makeRequest
是重新加载通过AJAX的一些内容的功能。
function proxy()
{
/* implement call to your Ajax method */
}
setInterval(proxy, 1000); // last arg is in milliseconds
You can use serInterval method of javascript:
Just write down the lines at the bottom of your page:
<script>
window.setInterval(function(){
ajaxCallFunction(); //calling every 5 seconds
}, 5000);
function ajaxCallFunction(){
//this function uses ajax to interact with the server
}
<script>
我假定存在与URL模式一个servlet /使用UpdateCount是在web.xml配置成提供动态数据/内容和有一个div元素countStatDiv在jsp页面。
下面的代码刷新使用GET方法和可变秒值可以根据需要而改变每隔30秒在/更新的countStatDiv内容:
<script>
var request;
var seconds=30;
function getRequestObject(){
setInterval(function() {sendRequest();},seconds*1000);
if (window.ActiveXObject){
return (new ActiveXObject("Microsoft.XMLHTTP"));
} else if (window.XMLHttpRequest){
return(new XMLHttpRequest());
} else {
return (null);
}
}
function sendRequest(){
request = getRequestObject();
request.onreadystatechange = handleResponse;
request.open("GET", "../UpdateCount", true);
request.send(null);
}
function handleResponse(){
if((request.readyState == 4)&&(request.status == 200)){
var serverResponse = request.responseText;
var statCtrl=document.getElementById("countStatDiv");
statCtrl.innerHTML=serverResponse;
}
}
</script>
由于setTimeout和setInterval的已上面提到的,你应该看看John Resig关于定时器如何在JavaScript中工作的注意事项 - http://ejohn.org/blog/how-javascript-timers-work/ – 2009-08-29 04:45:10
看着jQuery库 - 看起来很流行插件设计专门做了我以后的工作:http://www.360innovate.co.uk/blog/2009/03/periodical updater-for-jquery/ – aaa90210 2009-08-29 13:10:46