Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$.getJSON get status

Perform cross domain query, how to perform a certain function if the URL on which it is running is not available (404)? I try something like this:

$.getJSON({
url:'example.php?callback=?',
statusCode: {
404:function(){alert('404');}
},
success :function(data){//do stuff}
});
like image 651
Aleksov Avatar asked Nov 12 '12 17:11

Aleksov


People also ask

What does getJSON mean?

The getJSON() method is used to get JSON data using an AJAX HTTP GET request.

What does jQuery getJSON return?

The jQuery. getJSON( url, [data], [callback] ) method loads JSON data from the server using a GET HTTP request. The method returns XMLHttpRequest object.

What are the arguments of getJSON method?

It is a callback function that executes on the successful server request. It also has three parameters that are data, status, and xhr in which data contains the data returned from the server, status represents the request status like "success", "error", etc., and the xhr contains the XMLHttpRequest object.

What is the difference between getJSON and Ajax in jQuery?

getJSON() is equal to $. ajax() with dataType set to "json", which means that if something different than JSON is returned, you end up with a parse error. So you were mostly right about the two being pretty much the same :).


2 Answers

I found this approach to solve the similar question I had, where I wanted to handle specific status codes differently. For example the '404' code as below.

$.getJSON(AJAX_URL, function(data) {
    //On Success do something.

}).fail(function(jqXHR) {
    if (jqXHR.status == 404) {
        alert("404 Not Found");
    } else {
        alert("Other non-handled error type");
    }
});

There are 3 parameters passed to the fail method:

jqXHR.fail(function(jqXHR, textStatus, errorThrown) {});

An alternative construct to the error callback option, the .fail() method replaces the deprecated .error() method. Refer to deferred.fail() for implementation details.

For the jQuery docs see:
http://api.jquery.com/jQuery.ajax/#jqXHR
http://api.jquery.com/deferred.fail/

like image 64
toddles_fp Avatar answered Sep 23 '22 04:09

toddles_fp


 $.getJSON({
       url:'example.php?callback=?'       
    },
      success :function(data){//do stuff}
    })
    .error(function(e, x) { if (x.status == 404) alert('404 - page was not available'); });
like image 41
humblelistener Avatar answered Sep 20 '22 04:09

humblelistener