XMLHttpRequest 总是得到一个空的响应,而通过浏览器直接 ping 同一个 url 得到正确的响应 [英] XMLHttpRequest always gets an empty response, while directly pinging the same url via browser gets the right response
问题描述
这是我的 javascript 片段:
Here is my javascript snippet:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {
...
}
}
}
var url = 'http://localhost:3000/questions/1';
xhr.open('GET', url, true);
xhr.send();
this.status 始终为 0,而 this.responseText 始终为 ""
this.status is always 0, and this.responseText is always ""
如果我直接从浏览器 ping url 'http://localhost:3000/questions/1',我会得到正确的 html.
If i ping the url 'http://localhost:3000/questions/1' directly from the browser, i get the correct html back.
仅供参考,我正在 ping 在我的机器上运行的 Rails 服务器.
FYI, i am pinging a rails server i am running on my machine.
推荐答案
我会尝试在您的代码中用 xhr
替换 this
.函数声明将通过闭包保留 xhr
变量.我不确定当函数被回调时 this
会是什么.
I would try replacing this
with xhr
in your code. The function declaration will keep the xhr
variable via the closure. I am not sure what this
will be when the function is called back.
这篇关于XMLHttpRequest 总是得到一个空的响应,而通过浏览器直接 ping 同一个 url 得到正确的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!