如何在没有互联网连接时提醒用户 [英] How to alert the user when there's no internet connection

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

问题描述

我需要提醒用户以下条件:

I need to alert the user with the following conditions;


  1. 请求超时

  2. 没有互联网连接

  3. 无法访问服务器

如何在发生时捕获以下条件并提醒用户?

Here's the code; How to capture the following conditions when occurred and alert the user ?

failure: function (response) {
    var text = response.responseText;
    console.log("FAILED");
},success: function (response) {
    var text = response.responseText;
    console.log("SUCCESS");
}

我试过下面的代码来检查互联网是否可达, 't work

I tried the following code to check if the internet is reachable, but it didn't work

var networkState = navigator.network.connection.type
    alert(states[networkState]);
    if (networkState == Connection.NONE){
        alert('No internet ');
    };

UPDATE **

我在我的index.html添加了以下内容,但是,当我禁用WIFI,我没有看到警报弹出。

I added the following in my index.html, but, when i disable WIFI, i don't see the alert popping.

<script>
function onDeviceReady() {
    document.addEventListener("offline", function() {
        alert("No internet connection");
    }, false);
}
</script>


推荐答案

最好的做法是听 离线事件。

The best thing to do is to listen to the "offline" event. When you get the offline event you can warn your user and take whatever steps necessary to save data, etc.

例如,您的deviceready回调:

For instance, your "deviceready" callback:

document.addEventListener("offline", function() {
    alert("No internet connection");
}, false);

此代码应适用于大多数所有版本的PhoneGap。至少从1.0版本开始。

This code should work for most all versions of PhoneGap. It's been in since at least the 1.0 release.

这篇关于如何在没有互联网连接时提醒用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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