需要捕获ajax crossdomain脚本加载错误

时间:2015-10-19 19:40:03

标签: javascript jquery ajax cross-domain

我在过去的一个月里处理过这个问题,我已经在stackoverflow上阅读了几乎所有的帖子,但是没办法......我最好的方法是:

$.ajax({
    url: "https://connect1.facebook.net/" + ('BR' == $('#country').val() ? 'pt_BR' : 'es_LA') + "/sdk.js",
    dataType: "script",
    cache: false,
    xhr: function () {

        var xhr = new window.XMLHttpRequest();

        //Not working...                           
        xhr.onerror = function(e) {
            alert("Error Status: " + e.target.status);
        };
        //Frustration ends here...

        return xhr;

    }
})
.done(function(data) {
    console.log("Ajax success");
    init();
    callback();                
});

“connect1”使请求失败,但由于跨域请求的着名问题,我无法找到捕获错误的方法。我最好的选择是实现我自己的xhr对象,但不会触发onerror事件。

我写这篇文章是因为任何新的或新鲜的想法都会对我有所帮助。

更新:这是您可以用来复制请求的网址,意图失败:https://connect1.facebook.net/es_LA/sdk.js?_=1445285186108

非常感谢。

吉列尔莫

2 个答案:

答案 0 :(得分:0)

要检查与脚本错误不同的响应代码,请向ajax添加statusCode回调。

$.ajax({
    url: "https://connect1.facebook.net/" + ('BR' == $('#country').val() ? 'pt_BR' : 'es_LA') + "/sdk.js",
    dataType: "script",
    cache: false,
    statusCode: {
        404: function() {
            alert( "page not found" );
        }
    },
    xhr: function () {

        var xhr = new window.XMLHttpRequest();

        //Not working...                           
        xhr.onerror = function(e) {
            alert("Error Status: " + e.target.status);
        };
        //Frustration ends here...

        return xhr;

    }
})
.done(function(data) {
    console.log("Ajax success");
    init();
    callback();                
});

另外,由于URL似乎是JS,并且您反对使用JQuery,为什么不使用jQuery.getScript()?

$.getScript( "https://connect1.facebook.net/" + ('BR' == $('#country').val() ? 'pt_BR' : 'es_LA') + "/sdk.js");

答案 1 :(得分:-1)

最后,感谢帮助了我很多的@Wobbles,我们在这里找到了答案:

https://stackoverflow.com/a/19101142/943082

解决方案包括为ajax请求添加超时。

超时结束后,将触发onerror事件,然后您可以使用代码响应错误。

        $.ajax({
            url: "https://connect.facebook.net/" + ('BR' == $('#country').val() ? 'pt_BR' : 'es_LA') + "/sdk.js",
            dataType: "script",
            cache: false,
            timeout: 5000, // Wait 5 secs to get the sucess
            error: function(jqXHR, textStatus, errorThrown) {
                if(textStatus === "timeout") {
                    //We waited 5 secs and the request hasnt succeed.
                    //Code to manage the error.


                }
            }
        })

此致

吉列尔莫