检查是否连接到网络;jQuery

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9526647/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:56:01  来源:igfitidea点击:

Check if connected to a network; jQuery

jqueryhtml

提问by Brendan Lesniak

I have searched through StackOverflow and have seen various topics on how to do this, but nothing that really pertains to my particular situation. I am writing (for a class) a mobile "application" (using HTML5, CSS, jQuery). It will end up being a stand alone "app", something that will contain a local copy of all the needed files. On one of my pages I have a submit form, and since the user can't submit the form if they are offline, I would like the page to be redirected to a custom 404 page.

我搜索了 StackOverflow 并看到了有关如何执行此操作的各种主题,但没有与我的特定情况真正相关的主题。我正在(为一个班级)编写一个移动“应用程序”(使用 HTML5、CSS、jQuery)。它将最终成为一个独立的“应用程序”,其中包含所有所需文件的本地副本。在我的一个页面上,我有一个提交表单,由于用户离线时无法提交表单,因此我希望将该页面重定向到自定义 404 页面。

I was just searching to see if there was a way to accomplish this in jQuery, as I haven't really found anything yet.

我只是想看看是否有办法在 jQuery 中实现这一点,因为我还没有真正找到任何东西。

Thanks

谢谢

回答by Bot

You could use

你可以用

if (navigator.onLine) {
    // I'm online so submit the form.
}

回答by Petr Vostrel

You actually don't need jQuery for this at all. HTML5 itself has a neat facility for applications ran in online/offline conditions - cache manifest. The cache manifest is a plain text file referenced in the manifestattribute of <html>tag:

实际上,您根本不需要 jQuery。HTML5 本身具有适用于在线/离线条件下运行的应用程序的简洁工具 -缓存清单。缓存清单是在标签manifest属性中引用的纯文本文件<html>

<html manifest="cache.manifest">

The contents of this manifest file tells the browser, which resources need online conditions to function (NETWORK), which files to cache (CACHE) and what to do when network resource is requested while offline (FALLBACK).

这个清单文件的内容告诉浏览器,哪些资源需要在线条件才能运行 ( NETWORK),哪些文件要缓存 ( CACHE) 以及在离线状态下请求网络资源时要做什么 ( FALLBACK)。

CACHE MANIFEST
# the above line is required

NETWORK:
*

FALLBACK:
*   error404.html

CACHE:
index.html
about.html
help.html
# Plus all other resources required to make it look nice
style/default.css
images/logo.png
images/backgound.png

When using manifest, browser first consults the manifest and, without any scripting, acts accordingly based on being online or offline.

使用 manifest 时,浏览器首先查询 manifest,并在没有任何脚本的情况下根据在线或离线进行相应的操作。

http://dev.w3.org/html5/spec-preview/offline.html#manifests

http://dev.w3.org/html5/spec-preview/offline.html#manifests

UPDATE:

更新:

Please note the crucial requirement on response content type. Plain text simply doesn't work.

请注意响应内容类型的关键要求。纯文本根本不起作用。

Manifests must be served using the text/cache-manifestMIME type.

必须使用text/cache-manifestMIME 类型提供清单。

http://dev.w3.org/html5/spec-preview/offline.html#writing-cache-manifests

http://dev.w3.org/html5/spec-preview/offline.html#writing-cache-manifests

Also be aware that all URLs not listed in the manifest are blocked from load as a result. That's why I've fixed the above manifest with wildcards (*) to allow "the rest". That might help you get started.

另请注意,清单中未列出的所有 URL 都会因此被阻止加载。这就是为什么我用通配符 ( *)修复了上述清单以允许“其余部分”。这可能会帮助您入门。

回答by Jasper

You can either check the navigator.onLineproperty or listen to the offline/onlineevents:

您可以检查navigator.onLine属性或收听offline/online事件:

$(document).on('offline online', function (event) {
    alert('You are ' + event.type + '!');
});

Source: http://www.html5rocks.com/en/mobile/workingoffthegrid/

来源:http: //www.html5rocks.com/en/mobile/workingoffthegrid/

And here are some MDN docs for these events: https://developer.mozilla.org/en/Online_and_offline_events

以下是这些事件的一些 MDN 文档:https: //developer.mozilla.org/en/Online_and_offline_events

I'm not familiar with these events myself, but if you read the above links, you should find a lot of good information.

我自己对这些事件并不熟悉,但是如果您阅读上述链接,您应该会找到很多不错的信息。

回答by Brendan Lesniak

I'm using the following code to check for connectivity. NOTE: none of the solutions above work for Firefox, which relies on its internal 'Work Offline' status:

我正在使用以下代码来检查连接。注意:上述解决方案都不适用于 Firefox,它依赖于其内部的“离线工作”状态:

// Register listeners
window.addEventListener("offline", function(){
    $('#globalDiv').hide();
    $("#message").html('WARNING: Internet connection has been lost.').show();
});
window.addEventListener("online", function(){
    $("#message").empty().hide();
    $('#globalDiv').show();
});

回答by PraveenVenu

try to set up ajaxSetup to do a request every n milliseconds (i put 1000 here) and check if it times out and then disable button.

尝试将 ajaxSetup 设置为每 n 毫秒执行一次请求(我将 1000 放在这里)并检查它是否超时然后禁用按钮。

$.ajaxSetup({
    timeout: 1000, 
    error: function(request, status, maybe_an_exception_object) {
        if(status != 'timeout')
            //Code to enable button
        else
             //Code to disable button
    }
});

回答by Layke

Using window.navigator.onLineis inherantly unreliable, because the user might be connected to a network, but that network could not have internet access.

使用window.navigator.onLine本质上是不可靠的,因为用户可能已连接到网络,但该网络无法访问 Internet。

However, here is a barebones example

但是,这是一个准系统示例

<!DOCTYPE HTML>
<html>
 <head>
  <title>Online status</title>
  <script>
   function updateIndicator() {
     document.getElementById('indicator').textContent = navigator.onLine ? 'online' : 'offline';
   }
  </script>
 </head>
 <body onload="updateIndicator()" ononline="updateIndicator()" onoffline="updateIndicator()">
  <p>The network is: <span id="indicator">(state unknown)</span>
 </body>
</html>?

See the fiddle in action: http://jsfiddle.net/3rRWK/

看到小提琴在行动:http: //jsfiddle.net/3rRWK/

回答by Todd Moses

Here is what I would do, based upon: how to check if the user has the connection to the internet

这是我会做的,基于:如何检查用户是否连接到互联网

First, use a javascript library link to determine if user is online. If true change the action property of your form to the online page, else the offline page.

首先,使用 javascript 库链接来确定用户是否在线。如果为 true,将表单的 action 属性更改为在线页面,否则为离线页面。

    <script src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js></script>
    <script>
$('#target').submit(function() {
   if (typeof window.$ !== 'function') {
    $('myform').attr( "action" , "offlinepage.html"  );
   }
   else
   {
    $('myform').attr( "action" , "onlinepage.html"  );
   }
});
    </script>