Search code examples
jqueryjquery-1.5

Can you defer statusCode in jquery 1.5?


I see that they added a function for status codes

statusCode(added 1.5)Map Default: {} A map of numeric HTTP codes and functions to be called when the response has the corresponding code. For example, the following will alert when the response status is a 404:

$.ajax({   statusCode: {404: function() {
    alert('page not found');   } }); 

If the request is successful, the status code functions take the same parameters as the success callback; if it results in an error, they take the same parameters as the error

I am wondering can you do something like $.ajax({...}).statusCode(function(){...});

Simliar to how you can do

var jqxhr = $.ajax({ url: "example.php" })
    .success(function() { alert("success"); })
    .error(function() { alert("error"); })
    .complete(function() { alert("complete"); })

Solution

  • Yes, you can. The function is, as far as I can tell, undocumented, but the functionality seems to be exactly as you'd expect -- you pass in an object map of handler functions where the key is the HTTP response code and the value is the handler function. See the source code.

    Example

    $.ajax({ url: "example.php" })
        .statusCode({
            200: function(){
                alert('success');
            },
            404: function(){
                alert('not found');
            }
        });