Determine if $.ajax error is a timeout

后端 未结 1 1619
孤城傲影
孤城傲影 2020-11-22 14:04

I\'m utilizing the magic of jQuery.ajax( settings ).

However, I\'m wondering if anyone has played with the timeout setting much?

I know it\'s ba

相关标签:
1条回答
  • 2020-11-22 14:18

    If your error event handler takes the three arguments (xmlhttprequest, textstatus, and message) when a timeout happens, the status arg will be 'timeout'.

    Per the jQuery documentation:

    Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".

    You can handle your error accordingly then.

    I created this fiddle that demonstrates this.

    $.ajax({
        url: "/ajax_json_echo/",
        type: "GET",
        dataType: "json",
        timeout: 1000,
        success: function(response) { alert(response); },
        error: function(xmlhttprequest, textstatus, message) {
            if(textstatus==="timeout") {
                alert("got timeout");
            } else {
                alert(textstatus);
            }
        }
    });​
    

    With jsFiddle, you can test ajax calls -- it will wait 2 seconds before responding. I put the timeout setting at 1 second, so it should error out and pass back a textstatus of 'timeout' to the error handler.

    Hope this helps!

    0 讨论(0)
提交回复
热议问题