Capture 404 status with jQuery AJAX

后端 未结 2 1586
醉酒成梦
醉酒成梦 2020-12-01 12:51

I have this code:

$.ajax({ cache: false,
    url: \"/Admin/Contents/GetData\",
    data: { accountID: AccountID },
    success: function (data) {
        $(\         


        
相关标签:
2条回答
  • 2020-12-01 13:01

    404 erros will be handled by the anonymous function hooked up to the error property. Anything other than a successful HTTP request to the URL (i.e. 2xx) will trigger the error method. The following will work for your purpose:

    error : function(jqXHR, textStatus, errorThrown) { 
        if(jqXHR.status == 404 || errorThrown == 'Not Found') 
        { 
            console.log('There was a 404 error.'); 
        }
    }
    

    When they refer to removing the success and error functions in the jQuery documentation, they're referring to those of the jqXHR class, not the properties of $.ajax().

    0 讨论(0)
  • 2020-12-01 13:14

    Replace your error function as follows...

    error:function (xhr, ajaxOptions, thrownError){
        if(xhr.status==404) {
            alert(thrownError);
        }
    }
    
    0 讨论(0)
提交回复
热议问题