【发布时间】:2016-12-22 09:15:47
【问题描述】:
我正在尝试在 js 中检查互联网连接:
function doesConnectionExist() {
var xhr = new XMLHttpRequest();
var file = "https://www.google.com";
var randomNum = Math.round(Math.random() * 10000);
xhr.open('HEAD', file + "?rand=" + randomNum, true);
xhr.send();
xhr.addEventListener("readystatechange", processRequest, false);
function processRequest(e) {
if (xhr.readyState == 4) {
if (xhr.status >= 200 && xhr.status < 304) {
alert("connection ok");
} else {
alert("connection doesn't exist!");
}
}
}
}
它不工作,显示:
连接不存在!
如果我通过“localhost/myApp”而不是“www.google.com”,它可以正常工作, 但如果我传递我的 IP 而不是“localhost”,那么它就不能再工作了。
【问题讨论】:
-
Javascript 默认会阻止所有跨站 ajax 请求。它只适用于你的本地主机。
-
看起来像跨域 Ajax 调用问题。
-
如何解决。任何建议请..
标签: javascript xmlhttprequest connection