how to schedule ajax calls every N seconds?

2019-01-20 10:28发布

问题:

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

回答1:

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.



回答2:

function proxy()
{
  /* implement call to your Ajax method */
}

setInterval( proxy, 1000 ); // last arg is in milliseconds


回答3:

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>


回答4:

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>