2

我一直在尝试使用 jquery-ajax 从我的服务器下载二进制文件,但最终我放弃了。所以现在我尝试改用 XMLHttpRequest 。但是,我什至无法获得一个简单的示例。

奇怪的是,这段代码似乎没有做任何事情。我从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 函数一次,在xhttp.readyState 等于 one的open()语句中,而不是在send()步骤中。我应该认为它至少会抛出某种错误,而不是什么都不做。

另外,作为一个实验,我故意给 open() 提供了一个错误的 url - 但同样没有回复。

谁能告诉我我可能做错了什么?

非常感谢你。

4

1 回答 1

2

您的代码对我来说看起来是正确的,这指向了一些外部原因。

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

例如:

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){}

永远不会拨打电话。

于 2016-01-05T20:47:27.707 回答