http://www.w3.org/TR/access-control/
Reading the CORS spec linked above, it seems to be the case that it's impossible to reliably distinguish between a generic "network error" and a cross-origin access denied error. From the spec:
If there is a network error Apply the network error steps.
Perform a resource sharing check. If it returns fail, apply the network error steps.
http://www.w3.org/TR/access-control/#simple-cross-origin-request0
In my testing, I couldn't locate any features of Firefox's implementation that seem to indicate that the resource sharing check definitely failed. It just switches readyState to 4 and sets status to 0.
Ultimately I'd like 开发者_开发技巧the ability to pass a success callback, a general fail callback, and an optional cross-origin fail callback, to my function. Thanks for any help or insight.
You likely do not need to make the XHR request to know when a cross-origin error is going to occur. Try the following based on jQuery's $.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"))
);
}
};
精彩评论