Created
May 10, 2012 18:56
-
-
Save michaelcox/2655118 to your computer and use it in GitHub Desktop.
Adds XDomainRequest IE CORS support to jQuery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Based on https://github.com/jaubourg/ajaxHooks/blob/master/src/ajax/xdr.js | |
(function( jQuery ) { | |
if ( window.XDomainRequest && !jQuery.support.cors ) { | |
jQuery.ajaxTransport(function( s ) { | |
if ( s.crossDomain && s.async ) { | |
if ( s.timeout ) { | |
s.xdrTimeout = s.timeout; | |
delete s.timeout; | |
} | |
var xdr; | |
return { | |
send: function( _, complete ) { | |
function callback( status, statusText, responses, responseHeaders ) { | |
xdr.onload = xdr.onerror = xdr.ontimeout = xdr.onprogress = jQuery.noop; | |
xdr = undefined; | |
jQuery.event.trigger( "ajaxStop" ); | |
complete( status, statusText, responses, responseHeaders ); | |
} | |
xdr = new XDomainRequest(); | |
xdr.open( s.type, s.url ); | |
xdr.onload = function() { | |
var status = 200; | |
var message = xdr.responseText; | |
var r = JSON.parse(xdr.responseText); | |
if (r.StatusCode && r.Message) { | |
status = r.StatusCode; | |
message = r.Message; | |
} | |
callback( status , message, { text: message }, "Content-Type: " + xdr.contentType ); | |
}; | |
xdr.onerror = function() { | |
callback( 500, "Unable to Process Data" ); | |
}; | |
xdr.onprogress = function() {}; | |
if ( s.xdrTimeout ) { | |
xdr.ontimeout = function() { | |
callback( 0, "timeout" ); | |
}; | |
xdr.timeout = s.xdrTimeout; | |
} | |
xdr.send( ( s.hasContent && s.data ) || null ); | |
}, | |
abort: function() { | |
if ( xdr ) { | |
xdr.onerror = jQuery.noop(); | |
xdr.abort(); | |
} | |
} | |
}; | |
} | |
}); | |
} | |
})( jQuery ); |
This works fine on my work network. It fails when using my 3G mobile network. Why is this so ? EI9
I am getting an error....'JSON' is undefined .....at line 26
THANKS
I spent a full day to fix an issue with ie. I really appreciate you shared this code, Thanks!! 😃
Thanks, it really helps a lot!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
26: var r = JSON.parse(xdr.responseText);
is it correct to assume that all responses are going to be JSON?