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

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

问题描述

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

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 ');
    };

更新**

我在我的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天全站免登陆