XMLHttpRequest 在 IE11 上很奇怪,在 Edge 和 Chrome 上正常

XMLHttpRequest strange on IE11, ok on Edge and Chrome

我尝试做以下事情 但它在我的情况下不适用于 IE11?

var request = new XMLHttpRequest();

function doStuff()
{
 console.log("next request");
 doRequest();     
}

function doRequest() {
 request.open("GET","http://127.0.0.1/poll.php", true);
 request.onloadend = doStuff;
 request.send();
}

doRequest();

PHP 脚本 poll.php 正在休眠一秒钟。 现在要点:Egde 和 Chrome 大约每秒请求一次 但是 IE 没有,它以每秒 1000 个请求向日志发送垃圾邮件,而且它们甚至没有执行。

如果我删除无限循环,IE 正在执行一个请求, 如果它是一个无限循环,那么 IE 除了发送垃圾邮件之外什么都不做。

希望你能理解我并给我一个提示, 如何解决我的问题。

此致。

似乎 IE 缓存了请求,因此第二个和后续请求立即完成 - 运行 代码一次后,即使是第一个请求也会这样做

As a side note, I'm actually surprised other browsers don't cache XHR requests - at least, they don't seem to if the question is an accurate reflection of browser behaviour!

一种解决方案是将随机 "search"(或查询)字符串添加到 URL

function doRequest() {
    request.open("GET","http://127.0.0.1/poll.php?_"+Math.random(), true);
    //                                           ^^^^^^^^^^^^^^^^^
    request.onloadend = doStuff;
    request.send();
}

另一种方法是让服务器响应 headers 告诉浏览器 "don't cache this" - 在 PHP 的情况下(因为请求显然是针对 PHP)

header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

(无耻地从https://whosebug.com/a/13640164/5053002 "borrowed" - 所以如果错了不要怪我,我已经好几年没用过PHP了)