Capture 404 status with jQuery AJAX

喜你入骨 提交于 2019-11-26 20:25:06

问题


I have this code:

$.ajax({ cache: false,
    url: "/Admin/Contents/GetData",
    data: { accountID: AccountID },
    success: function (data) {
        $('#CityID').html(data);
    },
    error: function (ajaxContext) {
        alert(ajaxContext.responseText)
    }
});

I am still confused about the ajaxContext and how to capture 404 return codes. However I have another question. I am reading something about coding with success and fail and no longer using error in the recent versions of jQuery.

So should I change my code to use done and fail. How then could I check for a 404?


回答1:


Replace your error function as follows...

error:function (xhr, ajaxOptions, thrownError){
    if(xhr.status==404) {
        alert(thrownError);
    }
}



回答2:


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().



来源:https://stackoverflow.com/questions/10931270/capture-404-status-with-jquery-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!