Detect the Internet connection is offline?

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

How to detect the Internet connection is offline in JavaScript?

19条回答
  •  旧时难觅i
    2020-11-22 01:50

    You can use $.ajax()'s error callback, which fires if the request fails. If textStatus equals the string "timeout" it probably means connection is broken:

    function (XMLHttpRequest, textStatus, errorThrown) {
      // typically only one of textStatus or errorThrown 
      // will have info
      this; // the options for this ajax request
    }
    

    From the doc:

    Error: A function to be called if the request fails. The function is passed three arguments: The XMLHttpRequest object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror". This is an Ajax Event

    So for example:

     $.ajax({
       type: "GET",
       url: "keepalive.php",
       success: function(msg){
         alert("Connection active!")
       },
       error: function(XMLHttpRequest, textStatus, errorThrown) {
           if(textStatus == 'timeout') {
               alert('Connection seems dead!');
           }
       }
     });
    

提交回复
热议问题