To test what happens when I try to load a non-existent resource (on the same host as my web server), I set up the following code:
var wrongURL = "http://foo/bar.json"; // non-existent resource
$.ajax({
url: wrongURL,
dataType: 'json',
success: function(jsonResponse, textStatus, jqXHR) {
$.('#divOfInterest').html("you should never see this");
},
error: function(jqXHR, textStatus, errorThrown) {
$.('#divOfInterest').html("sorry, could not find URL");
}
});
// remainder of code...
Instead of seeing my div show the message sorry, could not find URL, I get a console error:
GET http://foo/bar.json 404 (Not Found) - bar.json
Anything within the error call and after the $.ajax() block (i.e., // remainder of code) does not get executed
It looks like my browser (Safari 5.1.5) is getting stuck on the 404 error and leaves the function early.
How do I get to handle the error gracefully and execute the rest of my code?
Just replace
$.('#divOfInterest')with$('#divOfInterest')😀Demo: http://jsfiddle.net/9Ua8J/