简体   繁体   中英

jQuery jsonp catch “Failed to load resources…”

I have a Javascript function where I get data via JSONP from my server. I have tried to simulate server errors or lack of internet access (it is supposed to run in a cordova app, so it's possible the client doesn't have internet access), but I can't catch the error. Here is my code:

var completed =  false;
jQuery.ajax({
    url: "http://www.someDomainThatDoesn'tWork.com/getsContent.php?callback=?",
    dataType: "json",
    success: function(data) {
        completed = true
        console.log(data);
    },
    error: function() {
        console.log("fail");            
    },
    statusCode: {
        404: function() {
            console.log("fail 2");
        }
    }
}).fail(function() {
    console.log("fail 3");
}).always(function() {
    if (!completed) {
        console.log("fail 4");
    }
});

As you can see I try to catch (different) errors in four places. However, if I for example edit the url to one that doesn't exist, the javascript just aborts and give me the error

Failed to load resource: the server responded with a status of 404 (Not Found)

and none of the error catchers gets executed.

In the documentation for jQuery.ajax() it says

Note: This handler is not called for cross-domain script and cross-domain JSONP requests. so I guess I shouldn't be surprised.

Is there any way to catch this error? I have also tried to embrace it with

try{} catch(error) {} 

but that doesn't do the trick either.

因为JSONP方法返回一个脚本,它可能会在无提示的情况下失败,所以您可能需要将服务器更改为使用CORS而不是使用JSONP才能获得正确的错误处理。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM