2016-12-22 4 views
1

のために働い:XMLHttpRequestが唯一、私は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!"); 
     } 
    } 
    } 
} 

その動作していない、示す:

接続が存在しません!

私が代わりに「www.google.com」の「ローカルホスト/ MyApp]を」渡した場合、それは、正常に動作します が、私が代わりに「localhost」が私のIPを渡すと、それは再びその時間を働いていません。

+0

JavascriptのすべてのクロスサイトAJAXリクエスト。これは、urローカルホストでのみ動作します。 –

+0

クロスドメインAjaxコールの問題のようです。 –

+0

解決方法任意の提案pls .. –

答えて

0

要件が単純な場合は、CORSを有効にしたプロキシサーバーを使用できます。同様のサービスを使用して独自の設定のプロキシサーバーを使用することもできます。単一のサーバーの稼働時間を確認しているだけの場合は、このサービスのためにサーバーでCORSを有効にすることをお勧めします。デフォルトのブロックによる

function doesConnectionExist(url) { 
 
    var xhr = new XMLHttpRequest(); 
 
    var file = "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); 
 

 
    function processRequest(e) { 
 
    if (xhr.readyState == 4) { 
 
     console.log(url, xhr.status); 
 
     if (xhr.status >= 200 && xhr.status < 304) { 
 

 
     console.log("connection ok"); 
 
     } else { 
 
     console.log("connection doesn't exist!"); 
 
     } 
 
    } 
 
    } 
 
} 
 
doesConnectionExist("http://www.marotikkaya.in"); 
 
doesConnectionExist("http://www.google.com");

関連する問題