我正在尝试通过 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/