JSONP error recovery for cross-domain request

I am using jQuery.getJSON() URL (another domain), which may not exist. Is there a way for me to catch the error "Could not load resource"? It seems that try / catch is not working due to the asynchronous nature of this call.

I can not use jQuery.ajax() " error: ". From the doc:

Note. This handler is not called for cross-domain script and JSONP requests.

+6
json javascript jquery jsonp error-handling
source share
4 answers

If you have an idea about the worst-case delay for a successful result being returned from a remote service, you can use the 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 
+11
source share

It works:

 j.ajaxSetup({ "error":function(xhr, ajaxOptions, thrownError) { console.log(thrownError); }}); 
+1
source share

Pending objects (new in jQuery 1.5) sound exactly the way you are looking for:

jQuery.Deferred, introduced in version 1.5, is a complete utility object that can register multiple callbacks in a callback queue, call callback queues, and relay the success or failure status of any synchronous or asynchronous function.

http://api.jquery.com/category/deferred-object/

EDIT:

The following code works great for me:

 function jsonError(){ $("#test").text("error"); } $.getJSON("json.php",function(data){ $("#test").text(data.a); }).fail(jsonError); 

json.php looks like this:

 print '{"a":"1"}'; 

The error function is triggered for me if the path to json.php is wrong or the JSON code is wrong. For example:

 print '{xxx"a":"1"}'; 
-2
source share

That you are complaining about a client-side error saying that you tried to download the resource from the server.

This is built into the browser and it allows your browser to inform the client or developers that the download of the resource from the Internet has failed. This has nothing to do with JavaScript and is a lower-level error that has attacked HTTP, which is caught by the browser.

If you need the hope that you will need to give up third-party ajax libraries and deal with the XMLHTTPRequest object at a much lower level, even then I doubt that you can do something about it.

Basically, when you see this error, find out which object you are trying to get, which does not exist or failed to get. Then either stop accessing it or make it available.

-6
source share

All Articles