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}
});
The getJSON() method is used to get JSON data using an AJAX HTTP GET request.
The jQuery. getJSON( url, [data], [callback] ) method loads JSON data from the server using a GET HTTP request. The method returns XMLHttpRequest object.
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.
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 :).
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/
$.getJSON({
url:'example.php?callback=?'
},
success :function(data){//do stuff}
})
.error(function(e, x) { if (x.status == 404) alert('404 - page was not available'); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With