getting the error response from an ajax request in jquery
My webserver returns an json response to any ajax request no matter what. If the response was a success, it returns the json with the status code of 200. If the开发者_开发百科re was something wrong, it'll return the json with a status code of 400 or 500. I need to get that information, even if the request is a 400 or 500 because the json response has the error message with it, which needs to be presented to the user.
The problem is that the jquery $.ajax function does not give you access to the response object if the status code is anything other than 200, correct? Is there a way to do this?
You could override the jQuery.httpSuccess
method used internally to determine if a request is successful, for example:
jQuery.httpSuccess = function() { return true; }
This will let your success
handler execute even on status codes in the 400/500 range.
Note: this may change to jQuery.ajax.httpSuccess
later.
Sure it does. The success
function is called only when the call was successful, but the error
callback is called when there's been an error — including an HTTP status other than 200.
$.ajax({..., error: function(XMLHttpRequest, textStatus, errorThrown) { ... } });
You can retrieve it easily :
$.ajax({
// your options
success: function(data, xhr) {
alert(xhr.status);
}
});
精彩评论