how to schedule ajax calls every N seconds?

前端 未结 4 1486
天命终不由人
天命终不由人 2020-12-02 02:17

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 sta

相关标签:
4条回答
  • 2020-12-02 02:31

    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>
    
    0 讨论(0)
  • 2020-12-02 02:36

    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.

    0 讨论(0)
  • 2020-12-02 02:38
    function proxy()
    {
      /* implement call to your Ajax method */
    }
    
    setInterval( proxy, 1000 ); // last arg is in milliseconds
    
    0 讨论(0)
  • 2020-12-02 02:42
    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>
    
    0 讨论(0)
提交回复
热议问题