Detect the Internet connection is offline?

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

How to detect the Internet connection is offline in JavaScript?

19条回答
  •  轮回少年
    2020-11-22 01:41

    request head in request error

    $.ajax({
        url: /your_url,
        type: "POST or GET",
        data: your_data,
        success: function(result){
          //do stuff
        },
        error: function(xhr, status, error) {
    
          //detect if user is online and avoid the use of async
            $.ajax({
                type: "HEAD",
                url: document.location.pathname,
                error: function() { 
                  //user is offline, do stuff
                  console.log("you are offline"); 
                  }
             });
        }   
    });
    

提交回复
热议问题