问题
I'm trying to make a asynchronous call to a service that returns json using XDomainRequest (IE8). The problem is that i always get an error (the onerror event is fired, and the responseText is always null), i'm using fiddler to check the response of the service and i seems right (I can see the json object returnig), this only happen in IE8 when using XDomainRequest, the same functionality implemented in JQuery works fine.
Any clue would be appreciated. Thanks!
P.S.: This is my javascript code:
.....
if (jQuery.browser.msie && window.XDomainRequest) {
//Use Microsoft XDR
var xdr = new XDomainRequest();
xdr.open("post", url);
xdr.onload = function () {
alert("Loading");
alert(xdr.responseText);
};
xdr.onsuccess = function() {
alert("Success!");
alert(xdr.responseText);
};
xdr.onerror = function() {
alert("Error!");
alert(xdr.responseText);
};
xdr.onprogress = function() {
alert("Progress");
alert(xdr.responseText);
};
xdr.timeout = 1000;
xdr.send("data: " + escape(data));
var response = xdr.responseText;
} else .....
回答1:
Are you sure that the service is sending a Access-Control-Allow-Origin-header matching the requesting URL?
回答2:
Your problem may be the content-type sent, because XDomainRequest only support "text/plain".
Reference: http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
Cheers,
Andre Pedroso
回答3:
A year old post,, you still there GiaNU?! You are calling xdr.onsuccess but I don't think that method exists. The xdr.onload works and seem to be equivalent to jQuery's AJAX "success" function.
This X-Domain stuff is quite new but there is a very nice working model available from MS now here: AJAX - Introducing Cross-domain Request (XDR)
The xdr.ontimeout I can't get to do a thing, but don't find a need yet :) I got things up and running first w/jQuery and now with ie9 thank's to the MS post.
The XDR has some trouble with the timing for my current application and is just used a timeout to handle it:
xdr.onload = setTimeout( function(){ doIt( xdr.responseText ), 2000});
回答4:
Another gotcha is if you're running the service via Cassini then the "Access-Control-Allow-Origin" header won't be returned as Cassini doesn't recognise this. We had a scenario where our service calls were working on a test server but not working locally. Turns out the service was hosted in Cassini on our local dev machine but hosted on IIS on the test server.
Also here's the web.config setting for anyone that needs it (note: this allows access from any domain - "*"):
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
来源:https://stackoverflow.com/questions/4739384/xdomainrequest-problem