XMLHttpRequest 似乎没有做任何事情

XMLHttpRequest does not seem to do anything

我一直在尝试使用 jquery-ajax 从我的服务器下载二进制文件,但没有成功,我最终放弃了。所以现在我正在尝试改用 XMLHttpRequest。但是,我什至不能让一个简单的例子起作用。

奇怪的是,这段代码似乎没有做任何事情。我 copy/pasted 来自 w3schools 并且此示例与许多其他示例几乎相同。它在 chrome 或 FF 中对我不起作用:

 var xhttp = new XMLHttpRequest();
 xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
       // Action to be performed when the document is read;
    }
};
xhttp.open("GET", '/blah/blah/output.png', true);
xhttp.send();

我们只进入 onreadystatechange 函数一次,在 open() 语句中 xhttp.readyState 等于 one ,但不在 send() 步骤。我认为它至少会抛出某种错误,而不是什么都不做。

另外,作为实验,我故意给 open() 喂了一个坏的 url - 但还是没有回复。

任何人都可以告诉我我可能做错了什么吗?

非常感谢。

你的代码在我看来是正确的,这指出了一些外部原因。

您的代码是否一直流到执行上下文的末尾?浏览器将保留网络请求,直到引擎让步给浏览器。

例如:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (xhttp.readyState == 4 && xhttp.status == 200) {
   // Action to be performed when the document is read;
  }
};
xhttp.open("GET", '/blah/blah/output.png', true);
xhttp.send();

while(true){}

永远不会发送呼叫。