I'm using jQuery.getJSON()
on a URL (different domain) which may not exist. Is there a way for me to catch the error "Failed to load resource"? It seems that try/catch doesn't work because of the asynchronous nature of this call.
I can't use jQuery.ajax()
's "error:
" either. From the documetation:
Note: This handler is not called for cross-domain script and JSONP requests.
JSONP stands for JSON with Padding. Requesting a file from another domain can cause problems, due to cross-domain policy. Requesting an external script from another domain does not have this problem. JSONP uses this advantage, and request files using the script tag instead of the XMLHttpRequest object.
JSONP is still useful for older browser support, but given the security implications, unless you have no choice CORS is the better choice.
JSONP has some other limitations, too: It can only be used for GET requests, and there's no general way to prevent cross-site request forgeries*. It's bad for private data, since any site on the web could hijack a JSONP response if the URL is known.
JSONP is vulnerable to the data source replacing the innocuous function call with malicious code, which is why it has been superseded by cross-origin resource sharing (available since 2009) in modern applications.
If you have an idea of the worst case delay of a successful result returning from the remote service, you can use a timeout mechanism to determine if there was an error or not.
var cbSuccess = false;
$.ajax({
url: 'http://example.com/.../service.php?callback=?',
type: 'get',
dataType: 'json',
success: function(data) {
cbSuccess = true;
}
});
setTimeout(function(){
if(!cbSuccess) { alert("failed"); }
}, 2000); // assuming 2sec is the max wait time for results
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