如果AJAX是异步的,为什么我们要使用setTimout函数

why do we use setTimout function if AJAX is asynchronous?

本文关键字:setTimout 函数 我们 为什么 AJAX 异步 如果      更新时间:2024-05-07

我一直在使用jquery库来实现AJAX。一切都很好,我对此感到很舒服。然而,我开始阅读一些ajax书籍,并发现了以下代码。

// stores the reference to the XMLHttpRequest object
var xmlHttp = createXmlHttpRequestObject();
// retrieves the XMLHttpRequest object
function createXmlHttpRequestObject()
{
    // will store the reference to the XMLHttpRequest object
    var xmlHttp;
    // if running Internet Explorer
    if(window.ActiveXObject)
    {
        try
        {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch (e)
        {
        xmlHttp = false;
        }
    }// if running Mozilla or other browsers
    else
    {
        try
        {
        xmlHttp = new XMLHttpRequest();
        }
        catch (e)
        {
        xmlHttp = false;
        }
    }
    // return the created object or display an error message
    if (!xmlHttp)
    alert("Error creating the XMLHttpRequest object.");
    else
    return xmlHttp;
}
// make asynchronous HTTP request using the XMLHttpRequest object
function process()
{
    // proceed only if the xmlHttp object isn't busy
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
    {
        // retrieve the name typed by the user on the form
        name = encodeURIComponent(document.getElementById("myName").value);
        // execute the quickstart.php page from the server
        xmlHttp.open("GET", "quickstart.php?name=" + name, true);
        // define the method to handle server responses
        xmlHttp.onreadystatechange = handleServerResponse;
        // make the server request
        xmlHttp.send(null);
    }
    else
    // if the connection is busy, try again after one second
    setTimeout('process()', 1000);
}

//executed automatically when a message is received from the server
function handleServerResponse()
{
    // move forward only if the transaction has completed
    if (xmlHttp.readyState == 4)
    {
        // status of 200 indicates the transaction completed successfully
        if (xmlHttp.status == 200)
        {
        // extract the XML retrieved from the server
        xmlResponse = xmlHttp.responseXML;
        // obtain the document element (the root element) of the XML structure
        xmlDocumentElement = xmlResponse.documentElement;
        // get the text message, which is in the first child of
        // the the document element
        helloMessage = xmlDocumentElement.firstChild.data;
        // update the client display using the data received from the server
        document.getElementById("divMessage").innerHTML =
        '<i>' + helloMessage + '</i>';
        // restart sequence
        setTimeout('process()', 1000);
        }
        // a HTTP status different than 200 signals an error
        else
        {
        alert("There was a problem accessing the server: " + xmlHttp.statusText);
        }
    }
}

这里我的问题是,为什么我们在handleServerResponse()函数中使用setTimeout('process()', 1000);?如果没有setTimeout('process()',1000);,我们就不能做到这一点吗;?

对我来说,它看起来像是某种常量轮询。它每秒都在重复使用AJAX请求,当前一个请求仍然处于活动状态时,它会再等一秒钟再发送。因此,这不仅仅是创建AJAX请求并处理响应

使用该代码,页面将不断更新从服务器检索到的信息。每当服务器响应发生变化时,页面也会发生变化,但不是实时的(只有在下一个请求完成时)。它类似于定期刷新。

作为一种进化,您可以使用Long Polling生成AJAX请求,然后等待服务器响应。如果服务器中有您的任何信息,您将立即收到回复。若在等待响应的过程中,有任何东西为您到达服务器,您将收到它。若您的请求超时,服务器将以一个空体进行响应。然后,您的客户端将生成另一个AJAX请求。你可以从维基百科上获得更多信息。额外链接:彗星。

在给定的例子中,本书对body onload事件调用了process()函数。当我将代码从onload->更改为onkeyup <input type="text" id="myName" onkeyup="process()"/>时,我可以删除代码//setTimeout('process()', 1000);