JQuery Ajax - How to Detect Network Connection error when making Ajax call

前端 未结 8 2223
闹比i
闹比i 2020-11-27 04:02

I have some Javascript JQuery code that does an Ajax call to the server every 5 mins, it\'s to keep the server session alive and keep the user logged in. I\'m using $.

8条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-27 04:33

    Since I can't duplicate the issue I can only suggest to try with a timeout on the ajax call. In jQuery you can set it with the $.ajaxSetup (and it will be global for all your $.ajax calls) or you can set it specifically for your call like this:

    $.ajax({
        type: 'GET',
        url: 'http://www.mywebapp.com/keepAlive',
        timeout: 15000,
        success: function(data) {},
        error: function(XMLHttpRequest, textStatus, errorThrown) {}
    })
    

    JQuery will register a 15 seconds timeout on your call; after that without an http response code from the server jQuery will execute the error callback with the textStatus value set to "timeout". With this you can at least stop the ajax call but you won't be able to differentiate the real network issues from the loss of connections.

提交回复
热议问题