javascript 如果有互联网连接,检测到 JQuery Mobile
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5626832/
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
JQuery Mobile Detected if there's internet Connection
提问by Satch3000
What is the best way to detect if there's internet connection or not on my mobile via my web app?
通过我的网络应用程序检测我的手机上是否有互联网连接的最佳方法是什么?
回答by Liza Daly
There's no code necessary for this -- it's part of the HTML5 API. Check the value of window.navigator.onLine
-- it will be false
if the user is offline.
这不需要任何代码——它是 HTML5 API 的一部分。检查值window.navigator.onLine
--false
如果用户处于离线状态。
http://www.whatwg.org/specs/web-apps/current-work/multipage/offline.html#browser-state
http://www.whatwg.org/specs/web-apps/current-work/multipage/offline.html#browser-state
回答by Charles
An option might be changing the Ajax settingsto add a specific timeout
, then add an error
handler that looks for a textStatus
(second argument) of 'timeout'
.
一个选项可能是更改 Ajax 设置以添加特定的timeout
,然后添加一个error
处理程序来查找 的textStatus
(第二个参数)'timeout'
。
When a timeout occurs, either internet connectivity is spotty or your site is down.
发生超时时,互联网连接不稳定或您的站点已关闭。
Using ajaxSetupto set option defaults for all requests:
使用ajaxSetup为所有请求设置选项默认值:
$.ajaxSetup({
timeout: 1, // Microseconds, for the laughs. Guaranteed timeout.
error: function(request, status, maybe_an_exception_object) {
if(status != 'timeout')
alert("YOU BROKE IT");
else
alert("OH NOES TEH INTARWEBS ARE DOWN!!!!!1one");
}
});
回答by user1208396
in simple JS code this can done, causation all featured devices not have JS supported however for web-based application this is very minimum code to use
在简单的 JS 代码中,这可以完成,原因是所有特色设备都不支持 JS,但是对于基于 Web 的应用程序,这是使用的最少代码
online = window.navigator.onLine;
if (navigator.onLine) {
alert('you are online');
} else {
alert('you are offline');
}
回答by Laniel D-Point
if you want to check every X seconds the connection.
如果你想每 X 秒检查一次连接。
$(document).ready(function() {
setInterval(function(){
var isOnline = navigator.onLine;
if (isOnline) {
console.log("Connected");
}
else {
console.log("Not Connected");
}
}, 30000); // 10000 = 10 seconds, check for connection every 30 seconds
});
回答by tripRev
If you want something with more compatibility, reliability and customisability than window.navigator.onLine, try my jQuery plugin: http://tomriley.net/blog/archives/111
如果你想要比 window.navigator.onLine 具有更多兼容性、可靠性和可定制性的东西,试试我的 jQuery 插件:http: //tomriley.net/blog/archives/111