如何使间隔不重叠的Ajax调用?间隔、Ajax

2023-09-10 16:40:30 作者:风带走故事也带走你

我期待建立一个网页,通过AJAX的样本数据中,从嵌入式web服务器调用。如何将我设置了code,这样一个请求但并不重叠的? 我要提到我很少JavaScript的经验,也是一个令人信服的理由不使用任何尺寸大于可能10个左右千字节的外部库。

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.

推荐答案

您可能要考虑重新发动你的AJAX请求后,只能从previous AJAX调用成功的响应的选项。

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);
        }
    }
}

本例使用 ExtJS的,但你可以很容易地只使用 XMLHtt prequest

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

注意:如果您必须有一个确切的时间间隔的 X 的秒钟,你就必须跟踪从经过的时间,当AJAX请求发起到的setTimeout()通话,然后减去这个时间跨度从延迟。否则,该间隔时间在上面的例子将随网络延迟和与时间处理web服务逻辑。

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.