javascript - 无法在 'send' 同步上执行 'XMLHttpRequest'

标签 javascript http

我正在尝试通过 JS 通过一个简单的获取请求连接到谷歌,它似乎总是给我同样的错误。

“无法在‘XMLHttpRequest’上执行‘发送’:无法加载‘http://google.com’。”

知道为什么会发生这种情况吗?相关代码如下。

        var xmlHttp = new XMLHttpRequest();
        xmlHttp.open("GET", "http://google.com", false);
        try {
            xmlHttp.send();
        } catch (err) {
            alert("EXCEPTION: " + err.message);
        }
        alert("here's the result of the get: " + xmlHttp.responseText);

最佳答案

由于same origin policy,这只是一个跨源权限失败。 .如果您异步运行相同的请求并查看您的控制台,您会看到更有用的错误消息:

XMLHttpRequest cannot load http://google.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://[whatever]' is therefore not allowed access.

这是因为只有在 http://www.google.com 的页面上运行的脚本才能读取 http://www.google.com 的资源。如果正在获取的资源提供适当的 CORS header (例如,Access-Control-Allow-Origin),您将不会看到此错误。 (但是,http://www.google.com 不提供此类 header )。

关于javascript - 无法在 'send' 同步上执行 'XMLHttpRequest',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34729084/

相关文章:

javascript - jQuery 鼠标事件不触发

javascript - 如何淡出然后直接到新页面

javascript - 禁用 iframe 标记中的下载按钮

xcode - 您可以使用 HLS 从 HTTPS 服务器流式传输吗?

c# - 使用 HTTP PUT 将文件上传到 Sharepoint (WSS 3.0) 文档库

http - header.Write/WriteSubset 的惯用用法是什么?

javascript - angularjs选择框设置对象值

javascript - 如何从现有的 json 对象创建新的 json 对象?

linux - Apache2虚拟主机文件

java - 415 不支持的媒体类型