是否可以区分网络错误和跨源错误?

时间:2010-05-18 21:27:21

标签: javascript xmlhttprequest

http://www.w3.org/TR/access-control/

阅读上面链接的CORS规范,似乎是无法可靠地区分通用“网络错误”和跨域访问拒绝错误的情况。来自规范:

  

如果出现网络错误请应用网络错误步骤。

     

执行资源共享检查。如果它返回失败,请应用网络错误步骤。

http://www.w3.org/TR/access-control/#simple-cross-origin-request0

在我的测试中,我找不到Firefox实现的任何功能,似乎表明资源共享检查肯定失败了。它只是将readyState切换为4并将状态设置为0。

最终,我希望能够将成功回调,一般失败回调和可选的跨源失败回调传递给我的函数。感谢您的帮助或见解。

1 个答案:

答案 0 :(得分:0)

您可能不需要让XHR请求知道何时会发生跨源错误。请尝试以下基于jQuery的$.get

var xhr = {
    get: function(url, data, callback, dataType) {
        if ( !this.isSameOrigin(url) ) {
            callback(null, "Same-origin error or whatever", null);
        }

        $.get(url, data, callback, dataType);
    },

    isSameOrigin: function(url) {
        // Do a string comparison against window.location.  Get as complicated 
        // as you'd like
        return !!(
            // Url doesn't contain a valid protocol (relative to domain))
            !url.match(/^https?:\/\//i) || 
            // Url contains a protocol but the request is to the current domain
            url.match(new RegExp("^https?://" + window.location.host, "i"))
        );
    }
};
相关问题