Detect the Internet connection is offline?

后端 未结 19 1381
甜味超标
甜味超标 2020-11-22 00:53

How to detect the Internet connection is offline in JavaScript?

19条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 01:30

    I had to make a web app (ajax based) for a customer who works a lot with schools, these schools have often a bad internet connection I use this simple function to detect if there is a connection, works very well!

    I use CodeIgniter and Jquery:

    function checkOnline() {
        setTimeout("doOnlineCheck()", 20000);
    }
    
    function doOnlineCheck() {
        //if the server can be reached it returns 1, other wise it times out
        var submitURL = $("#base_path").val() + "index.php/menu/online";
    
        $.ajax({
            url : submitURL,
            type : "post",
            dataType : "msg",
            timeout : 5000,
            success : function(msg) {
                if(msg==1) {
                    $("#online").addClass("online");
                    $("#online").removeClass("offline");
                } else {
                    $("#online").addClass("offline");
                    $("#online").removeClass("online");
                }
                checkOnline();
            },
            error : function() {
                $("#online").addClass("offline");
                $("#online").removeClass("online");
                checkOnline();
            }
        });
    }
    

提交回复
热议问题