使用jquery检查Internet连接 [英] Check Internet connectivity with jquery

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

问题描述

我正在尝试通过向服务器发送GET请求来检查互联网连接。我是jquery和javascript的初学者。我没有使用 navigator.onLine 代码,因为它在不同的浏览器中的工作方式不同。这是我到目前为止的代码:

I am trying to check for the internet connection by sending a GET request to the server. I am a beginner in jquery and javascript. I am not using navigator.onLine for my code as it works differently in different browsers. This is my code so far:

var check_connectivity={
        is_internet_connected : function(){
            var dfd = new $.Deferred();
            $.get("/app/check_connectivity/")
            .done(function(resp){
                return dfd.resolve();
            })
            .fail(function(resp){
                return dfd.reject(resp);
            })
            return dfd.promise();
        },
}

我将此代码称为不同的文件: / p>

I call this code in different file as:

if(!this.internet_connected())
        {
            console.log("internet not connected");
            //Perform actions
        }
internet_connected : function(){
        return check_connectivity.is_internet_connected();
},

is_internet_connected()函数返回一个延迟对象,而我只需要一个真/假的答案。谁能告诉我如何实现这个目标?

The is_internet_connected() function returns a deferred object whereas I just need an answer in true/false. Can anybody tell me about how to achieve this?

推荐答案

$。get()返回一个jqXHR对象,它是承诺兼容的 - 因此无需创建自己的 $。延期

$.get() returns a jqXHR object, which is promise compatible - therefore no need to create your own $.Deferred.

var check_connectivity = {
    ...
    is_internet_connected: function() {
        return $.get({
            url: "/app/check_connectivity/",
            dataType: 'text',
            cache: false
        });
    },
    ...
};

然后:

check_connectivity.is_internet_connected().done(function() {
    //The resource is accessible - you are **probably** online.
}).fail(function(jqXHR, textStatus, errorThrown) {
    //Something went wrong. Test textStatus/errorThrown to find out what. You may be offline.
});

正如您所看到的,无法确定您是在线还是离线。所有javascript / jQuery都知道资源是否被成功访问。

As you can see, it's not possible to be definitive about whether you are online or offline. All javascript/jQuery knows is whether a resource was successfully accessed or not.

一般来说,知道资源是否成功访问(以及响应很酷)比了解您的在线状态本身更有用。每个ajax调用都可以(并且应该)拥有自己的 .done() .fail()分支,允许适当的无论请求的结果如何都要采取的行动。

In general, it is more useful to know whether a resource was successfully accessed (and that the response was cool) than to know about your online status per se. Every ajax call can (and should) have its own .done() and .fail() branches, allowing appropriate action to be taken whatever the outcome of the request.

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

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