使用JavaScript检查互联网连接 [英] Checking internet connection using JavaScript

查看:95
本文介绍了使用JavaScript检查互联网连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题

如果WiFi关闭,我想显示警报[没有网络连接].在我的网页中,我有许多按钮,弹出窗口等.离线状态下,用户可以单击任何东西.但我想显示API调用是否失败.我可以在每次点击中检查navigator.onLine.但是我不想写函数调用或行数.有什么方法可以使用jQuery,JS,Ajax通常做到这一点?

I want to show an alert if WiFi is off [i.e. no internet connection]. In my web page, I have a number of buttons, pop-ups etc. User can click anything when offline. But I want to show if there is a failure in API call. I can check navigator.onLine in each click. But I dont want to write number of function calls or lines. Is there any way to do it commonly using jQuery, JS, Ajax?

当由用户操作引起的呼叫失败时,应显示ALERT"

"ALERT should be shown when call fails which caused by an user action"

$.ajax类似,但有错误.它不应与任何div/页面绑定.

Like $.ajax with error. It shouldn't be bounded with any div/page.

我尝试了以下操作:

navigator.onLine  // It works fine

我使用了以下提到的一种.但这不起作用.

I used the below one as mentioned. But it's not working.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.2.min.js"><\/script>')</script>     

我引荐的链接

检测到Internet连接处于脱机状态?

使用jquery检查Internet连接

还有一些.

有什么建议吗?

推荐答案

navigator.online检查是否存在网络,并且不检查互联网.如果您连接到没有互联网的网络,它仍将返回true

navigator.online checks if there is a network and don't check for internet. If you are connected to a network with no internet it will still return true

您可以使用对域的ajax请求进行检查

You can check using an ajax request to your domain

setInterval(function() {
  $.ajax({
    type: "HEAD",
    url: document.location.pathname + "?param=" + new Date(),
    error: function() {
      console.log(false);
    },
    success: function() {
      console.log(true);
    }
  });
}, 1000);

这篇关于使用JavaScript检查互联网连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆