【问题标题】:XMLHttpRequest always gets an empty response, while directly pinging the same url via browser gets the right responseXMLHttpRequest 总是得到一个空响应,而通过浏览器直接 ping 相同的 url 得到正确的响应
【发布时间】:2011-03-31 09:51:19
【问题描述】:

这是我的 javascript sn-p:

    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 始终为 ""

如果我直接从浏览器 ping url 'http://localhost:3000/questions/1',我会得到正确的 html。

仅供参考,我正在 ping 我的机器上运行的 Rails 服务器。

【问题讨论】:

  • 您从哪个域调用它?也是http://localhost:3000吗?
  • 确保主机:端口与same origin policy相同

标签: javascript ruby-on-rails xmlhttprequest


【解决方案1】:

我会尝试在您的代码中将this 替换为xhr。函数声明将通过闭包保留xhr 变量。我不确定当函数被回调时this 会是什么。

【讨论】:

    猜你喜欢
    • 2022-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-31
    • 1970-01-01
    • 2018-01-01
    相关资源
    最近更新 更多