Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/475.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
检查javascript中是否存在网络连接_Javascript_Jquery - Fatal编程技术网

检查javascript中是否存在网络连接

检查javascript中是否存在网络连接,javascript,jquery,Javascript,Jquery,我想用javascript检查运行时是否存在网络连接。我正在使用window.navigator.onLine,但它不工作 <script language="javascript"> alert(window.navigator.onLine); </script> 警报(window.navigator.onLine); 它总是返回true您可以尝试在短时间内使用AJAX调用并处理成功/错误。您可以按以下方式执行: if (navigator.onLine)

我想用javascript检查运行时是否存在网络连接。我正在使用window.navigator.onLine,但它不工作

<script language="javascript">

alert(window.navigator.onLine);

</script>

警报(window.navigator.onLine);

它总是返回true

您可以尝试在短时间内使用AJAX调用并处理成功/错误。

您可以按以下方式执行:

if (navigator.onLine) {
    alert("online");
}
var xhr = new XMLHttpRequest();
xhr.addEventListener('readystatechange', state_change, true);
xhr.open("GET", url, true);
xhr.send(null);

function state_change(){
   if(xhr.readyState == 4){
        if(xhr.status == 200){
          console.log('worked'); 
        } else if(xhr.status == 0) {
          console.log('no internet'); 
        } else {
          // Some other error
        } 
   }
}
或如下所示:

if (navigator.onLine) {
    alert("online");
}
var xhr = new XMLHttpRequest();
xhr.addEventListener('readystatechange', state_change, true);
xhr.open("GET", url, true);
xhr.send(null);

function state_change(){
   if(xhr.readyState == 4){
        if(xhr.status == 200){
          console.log('worked'); 
        } else if(xhr.status == 0) {
          console.log('no internet'); 
        } else {
          // Some other error
        } 
   }
}

你在哪个浏览器?不同的浏览器有不同的实现。例如,如果你可以连接到路由器,它认为你在线,即使你没有互联网连接,也可以在chrome上阅读