Domanda

I'm using ajax calls to retrieve some HTML data. In certain cases, there are chances that I may get HTTP error 403 (because of some IE bug Encountering 403 error while using ajax call on IE, Hash fragments with forward-slash throwing 403 errors with AJAX requests in IE).

For error handling purposes, I want to catch what error has occured and accordingly display some error message.

How do I do that?

Maybe something like

$.ajax({
    type : 'POST',
    data : data,
    cache : false,
    url : url,
    dataType : 'html'
    success : function(){
        //if HTTP response is ok, diplay data
        //else if HTTP response gets 403 error, display some other message
    }
});
È stato utile?

Soluzione

To quote the documentation:

error(jqXHR, textStatus, errorThrown)
Function
A function to be called if the request fails.
The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and JSONP requests.

$.ajax({
    type : 'POST',
    data : data,
    cache : false,
    url : url,
    dataType : 'html'
    success : function(){
        //if HTTP response is ok, diplay data
        //else if HTTP response gets 403 error, display some other message
    },
    error: function(){
        // Handle your error here
    }
});
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top