How do I make Ajax calls at intervals without overlap?

廉价感情. 提交于 2019-12-14 00:20:38

问题


I'm looking to setup a web page that samples data via AJAX calls from an embedded web-server. How would I set up the code so that one request doesn't overlap another? I should mention I have very little JavaScript experience and also a compelling reason not to use external libraries of any size bigger than maybe 10 or so kilobytes.


回答1:


You may want to consider the option of relaunching your AJAX request ONLY after a successful response from the previous AJAX call.

function autoUpdate()
{
    var ajaxConnection = new Ext.data.Connection();

    ajaxConnection.request(
    {
        method:         'GET',
        url:            '/web-service/', 

        success: function(response) 
        {
            // Add your logic here for a successful AJAX response.
            // ...
            // ...

            // Relaunch the autoUpdate() function in 5 seconds.
            setTimeout(autoUpdate, 5000);
        }
    }
}

This example uses ExtJS, but you could very easily use just XMLHttpRequest.

NOTE: If you must have an exact interval of x seconds, you would have to keep track of the time passed from when the AJAX request was launched up to the setTimeout() call, and then subtract this timespan from the delay. Otherwise, the interval time in the above example will vary with the network latency and with the time to processes the web service logic.




回答2:


AJAX, despite the name, need not be asynchronous.

Here is the asynchronous method...

var req;

function ajax(method,url,payload,action)
    {
    if (window.XMLHttpRequest)
        {
        req = new XMLHttpRequest();
        req.onreadystatechange = action;
        req.open(method, url, true);
        req.send(payload);
        }
    else if (window.ActiveXObject)
        {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req)
            {
            req.onreadystatechange = action;
            req.open(method, url, true);
            req.send(payload);
            }
        else
            {
            alert("Could not create ActiveXObject(Microsoft.XMLHTTP)");
            }
        }
    }

...but here is a synchronous equivalent...

function sjax(method,url,payload,action)
    {
    if (window.XMLHttpRequest)
        {
        req = new XMLHttpRequest();
        req.open(method, url, false);
        req.send(payload);
        action();
        }
    else if (window.ActiveXObject)
        {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req)
            {
            req.onreadystatechange = action;
            req.open(method, url, false);
            req.send(payload);
            }
        else
            {
            alert("Could not create ActiveXObject(Microsoft.XMLHTTP)");
            }
        }
    }

... and here is a typical action ...

function insertHtml(target)
    {
    var pageTarget = arguments[0];
    if (req.readyState == 4) // 4 == "loaded"
        {
        if (req.status == 200) // 200 == "Ok"
            {
            if (req.responseText.indexOf("error") >= 0)
                {
                alert("Please report the following error...");
                pretty = req.responseText.substring(req.responseText.indexOf("error"),1200);
                pretty = pretty.substring(0,pretty.indexOf("\""));
                alert(pretty + "\n\n" + req.responseText.substring(0,1200));
                }
            else
                {
                div = document.getElementById(pageTarget);
                div.innerHTML = req.responseText;
                dimOff();
                }
            }
        else
            {
            alert("Could not retreive URL:\n" + req.statusText);
            }
        }
    }



回答3:


I suggest you use a small toolkit like jx.js (source). You can find it here: http://www.openjs.com/scripts/jx/ (less than 1k minified)

To setup a request:

jx.load('somepage.php', function(data){
    alert(data); // Do what you want with the 'data' variable.
});

To set it up on an interval you can use setInterval and a variable to store whether or not a request is currently occuring - if it is, we simple do nothing:

var activeRequest = false;
setInterval(function(){

    if (!activeRequest) {
        // Only runs if no request is currently occuring:
        jx.load('somepage.php', function(data){
            activeRequest = false;
            alert(data); // Do what you want with the 'data' variable.
        });
    }
    activeRequest = true;

}, 5000); // Every five seconds


来源:https://stackoverflow.com/questions/1930975/how-do-i-make-ajax-calls-at-intervals-without-overlap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!