Javascript XMLHttpRequest仅适用于本地主机

Javascript XMLHttpRequest仅适用于本地主机,javascript,xmlhttprequest,connection,Javascript,Xmlhttprequest,Connection,我正在尝试检查js中的internet连接: 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()

我正在尝试检查js中的internet连接:

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!");
      }
    }
  }
}
函数doesConnectionExist(){
var xhr=new XMLHttpRequest();
变量文件=”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);
函数processRequest(e){
if(xhr.readyState==4){
如果(xhr.status>=200&&xhr.status<304){
警报(“连接正常”);
}否则{
警报(“连接不存在!”);
}
}
}
}
它不起作用,显示:

连接不存在

如果我通过了“localhost/myApp”而不是“www.google.com”,它就可以正常工作,
但是如果我通过我的IP而不是“localhost”,那么这一次就不再有效了。

如果您的要求很简单,您可以使用启用CORS的代理服务器。您甚至可以使用类似的服务设置自己的代理服务器。如果您只是检查单个服务器的正常运行时间,那么最好在服务器中为此服务启用CORS

函数doesConnectionExist(url){
var xhr=new XMLHttpRequest();
变量文件=”http://cors-anywhere.herokuapp.com/“+url;
var randomNum=Math.round(Math.random()*10000);
xhr.open('HEAD',file+“?rand=“+randomNum,true);
xhr.send();
xhr.addEventListener(“readystatechange”,processRequest,false);
函数processRequest(e){
if(xhr.readyState==4){
日志(url,xhr.status);
如果(xhr.status>=200&&xhr.status<304){
console.log(“连接正常”);
}否则{
log(“连接不存在!”);
}
}
}
}
是否存在连接(“http://www.marotikkaya.in");

是否存在连接(“http://www.google.com");如果您的要求很简单,您可以使用启用CORS的代理服务器。您甚至可以使用类似的服务设置自己的代理服务器。如果您只是检查单个服务器的正常运行时间,那么最好在服务器中为此服务启用CORS

函数doesConnectionExist(url){
var xhr=new XMLHttpRequest();
变量文件=”http://cors-anywhere.herokuapp.com/“+url;
var randomNum=Math.round(Math.random()*10000);
xhr.open('HEAD',file+“?rand=“+randomNum,true);
xhr.send();
xhr.addEventListener(“readystatechange”,processRequest,false);
函数processRequest(e){
if(xhr.readyState==4){
日志(url,xhr.status);
如果(xhr.status>=200&&xhr.status<304){
console.log(“连接正常”);
}否则{
log(“连接不存在!”);
}
}
}
}
是否存在连接(“http://www.marotikkaya.in");

是否存在连接(“http://www.google.com");Javascript会阻止所有跨站点ajax请求。它只适用于您的本地主机。它看起来像跨域Ajax调用问题。如何解决。任何建议请参考此Javascript的可能副本,默认情况下会阻止所有跨站点ajax请求。它只适用于您的本地主机。它看起来像跨域Ajax调用问题。如何解决。任何建议,请…你可以参考这个可能的副本