how to schedule ajax calls every N seconds?

2019-01-20 09:51发布

If I want a whole page to reload every N seconds, I would put something like this in the HTML: meta http-equiv="refresh" content="5"

Is there a standard practice for doing the same kind of thing for AJAX calls? I want schedule an AJAX call to go off every 10 seconds say, in order to update parts of the page, without refreshing the whole page. It would be even better if I could schedule multiple AJAX calls at different times, as some parts of the page may need to be updated more often than others.

TIA

4条回答
Ridiculous、
2楼-- · 2019-01-20 10:31

You could use setTimeout or setInterval (the latter is probably best suited to what you want to do).

setInterval(makeRequest, (10 * 1000));

...where makeRequest is a function that reloads some content via AJAX.

查看更多
该账号已被封号
3楼-- · 2019-01-20 10:34
function proxy()
{
  /* implement call to your Ajax method */
}

setInterval( proxy, 1000 ); // last arg is in milliseconds
查看更多
贼婆χ
4楼-- · 2019-01-20 10:50

I assume that there is a servlet with URL Pattern /UpdateCount is configured in web.xml to provide dynamic data/content and there is a div element countStatDiv in the jsp page.

The following code refreshes/updates the content of countStatDiv at every 30 seconds using GET method and variable seconds value can be changed according to the need:

                <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)&amp;&amp;(request.status == 200)){
                    var serverResponse = request.responseText;
                    var statCtrl=document.getElementById("countStatDiv");
                    statCtrl.innerHTML=serverResponse;
                    }
                    }
                </script>
查看更多
Deceive 欺骗
5楼-- · 2019-01-20 10:51
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>
查看更多
登录 后发表回答