javascript 收到响应后 XMLHttpRequest 对象是否关闭?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28099211/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Does XMLHttpRequest object close after response received?
提问by chRyNaN
I'm trying to connect to the server using an XMLHttpRequest object to post data at different times. I create an object and "connect" to the server like so:
我正在尝试使用 XMLHttpRequest 对象连接到服务器以在不同时间发布数据。我创建一个对象并“连接”到服务器,如下所示:
var xhr = new XMLHttpRequest();
xhr.open("post", location, true);
xhr.send(); //Is this send call needed to open the connection?
And at a later point in time, I call something like this:
在稍后的时间点,我会这样称呼:
xhr.send("Something to send");
However, looking at the developer console, it seems that only the initial request went through (and successfully responded). The second request doesn't seem to send. I'm trying to narrow down what could be the problem, so I thought: could the connection be closed once the response is received; Why would it be kept open? So, my question: Is the XMLHttpRequest object connection closed once it receives a response? If so, what's the best way to simulate a continuously open connection (to constantly reconnect?)?
但是,查看开发人员控制台,似乎只有初始请求通过(并成功响应)。第二个请求似乎没有发送。我试图缩小可能出现的问题的范围,所以我想:一旦收到响应,连接是否可以关闭?为什么要一直开着?所以,我的问题是:XMLHttpRequest 对象连接在收到响应后是否关闭?如果是这样,模拟持续打开的连接(不断重新连接?)的最佳方法是什么?
回答by Arnaud JOLLY
Yes, if you haven't tricked your server to keep it alive, it will be closed after the response is sent.
是的,如果你没有欺骗你的服务器让它保持活动状态,它会在响应发送后关闭。
Maybe you want to look for websockets. But if you don't want to play with those, just create a new HttpRequest for each of your "request".
也许你想寻找 websockets。但是如果你不想玩这些,只需为你的每个“请求”创建一个新的 HttpRequest 。
Basic communication with HTTP: 1 request -> 1 response -> closed!
与 HTTP 的基本通信:1 个请求 -> 1 个响应 -> 关闭!
Edit: Keep in mind that websockets is a new feature from HTML5 so it won't work for every browsers and if they work for some browsers, they maybe are not completely implemented.
编辑:请记住,websockets 是 HTML5 的一项新功能,因此它不适用于所有浏览器,如果它们适用于某些浏览器,则它们可能没有完全实现。