I have a simple PHP page (for testing) that simply calls header("Location: http://www.example.com");exit;
, which resides on the same server, in the same directory as another file with the following jQuery Javascript:
$(document).ready(function() {
jQuery.ajax({
type : 'GET',
url : 'bounce.php',
error : function(xhr, status, error) {
console.log("ERROR: ", xhr, xhr.status, xhr.getAllResponseHeaders());
},
complete : function(xhr, status) {
// Get headers of the response
console.log("COMPLETE: ", xhr, xhr.status, xhr.getAllResponseHeaders());
}
});
});
I was expecting (from several other StackOverflow responses) for the xhr.status
to return "302", but instead the AJAX call is triggering the "error" event (and then the "complete" even开发者_如何学JAVAt), and xhr.status
is returning 0
(zero), and .getAllResponseHeaders()
is coming back null
(in both the error, and complete functions).
Firebug is showing the "302 Moved Temporarily", and the response headers. So why is this triggering the error event, and not passing along the proper 302 code, and headers? Is this something to do with the Same Origin since the bouncing script and the fetching script are both on the same server? Is this jQuery or Javascript's fault?
XMLHttpRequest handles 301 and 302 errors transparently; that is, it treats the redirect as if you had hit the redirected URL in the first place, and that the redirect itself doesn't count as an event. When redirecting, it's like the original URL never even existed, so ultimately you're only going to end up with the status code that the final, redirected URL returns.
As a result, you're never going to end up with a 301 or 302 status code. So it sounds like you're running into what Amir mentioned, and the above policy is going to prevent you from capturing the desired status code to check for this condition.
I think the error is related to the browser security error. If you are not familiar with this, then you should know that using XMLHttpRequest you can only access files on the same server. So redirecting to example.com will result in an error because you are probably not on example.com.
So, with a combination of information from Amir and v64, I think I got it: The relevant points are
- Firebug does not necessarily use the same request as the XMLHttpRequest, so the headers may be different
- XMLHttpRequest cannot fetch files from remote servers (trying to fetch "http://www.example.com" directly fails)
- XMLHttpRequest handles redirects transparently, so a local file looks like a remote file to it.
End result: There's no way for Javascript alone to implement OpenID, it needs to fetch from scripts on the same server as itself that handle the remote file lookups.
And, the error response to an XMLHttpRequest doesn't give very informative errors when it encounters this security wall.
精彩评论