如果我要一整頁每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