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

前端 未结 8 2202
闹比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:24

    What I see in this case is that if I pull the client machine's network cable and make the call, the ajax success handler is called (why, I don't know), and the data parameter is an empty string. So if you factor out the real error handling, you can do something like this:

    function handleError(jqXHR, textStatus, errorThrown) {
        ...
    }
    
    jQuery.ajax({
        ...
        success: function(data, textStatus, jqXHR) {
            if (data == "") handleError(jqXHR, "clientNetworkError", "");
        },
        error: handleError
    });
    

提交回复
热议问题