5

当我不想从服务器返回响应时,是否有适当的方法进行 AJAX 调用?我希望服务器保存一些数据,但客户端不需要响应。如果服务器从不响应,AJAX 连接是否会保持打开状态,等待响应直到超时?

我会像下面这样使用Javascript。这是一个典型的 AJAX 调用,除了我省略了 xmlhttp.onreadystatechange 事件。

function SaveLabel()
{
    var xmlhttp = null;
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    } else {
        alert('Your browser does not support this feature.');
        return;
    }

    xmlhttp.open('GET', 'mypage.aspx?label=1');
    xmlhttp.send(null);
}

我发现了一个类似的问题,但它并没有真正回答我的问题:Ajax 连接是否在某些时候断开?

4

2 回答 2

6

You need to keep the connection open until the server is done with it, regardless of whether or not you expect (or will be or won't be) a reply from the server.

The reason is that most webservers will kill requests if the client disconnects before the script has finished executing.

The server doesn't have to "respond" as in return data, it just needs to "return".

i.e. in answer to your question "Does Ajax connection disconnect at some point?": Yes, when the server terminates the connection.

So what you need to do is make sure that your ASP(X) script terminates as soon as it has finished its work. Don't let it run forever, pass data to a helper daemon/service, etc. that will need long-running processing.

于 2012-05-22T05:10:28.983 回答
2

xmlhttp.onreadystatechange只是 XHR 对象的一个​​事件,您可以在其中附加一个侦听器以侦听它的状态变化。它与在页面上有一个按钮并添加一个onclick处理程序是同义的。

无论有没有处理程序,它都会做同样的事情(AJAX 仍然调用,按钮仍然是可点击的)。唯一的区别是你不知道刚刚发生了什么(你不知道 AJAX 是否成功/失败,你不知道按钮何时被点击)。

于 2012-05-22T05:20:10.820 回答