Catching a JSONP error on a cross-domain request

2020-03-20 07:14发布

问题:

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.

回答1:

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


回答2:

This works:

j.ajaxSetup({
    "error":function(xhr, ajaxOptions, thrownError) {   

    console.log(thrownError);                           
}});


回答3:

Deferred objects (new in jQuery 1.5) sound like exactly what you're looking for:

jQuery.Deferred, introduced in version 1.5, is a chainable utility object that can register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function.

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

EDIT:

The following code works fine 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 fires for me if the path to json.php is incorrect or if the JSON is malformed. For example:

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


回答4:

What your complaining about is a client-side error saying that you tried to download a resource from the server.

This is build into the browser and it allows your browser to tell the client or the developers that the downloading of a resource from the internet failed. This has nothing to do with JavaScript and is a more low level error thrown on the HTTP that is caught by the browser.

If you want any hope of catching it your going to need to drop 3rd party ajax libraries and deal with the XMLHTTPRequest object on a much lower level, even then I doubt you can do anything about it.

Basically when you see this error then find out what object your trying to get that doesn't exist or couldn't be accessed. Then either stop accessing it or make it accessible.