Pages

Monday, February 14, 2011

Javascript - Consume Service With Cross Domain Request

Every time you need to do a request over your domain, you have to be aware of what kind of browser is running your code. If is an IExplorer, you will need to use the object XDomainRequest because this object is specifically to make cross-domain requests.

Here's a sample of usage:









If you want to make it complaint with others browsers you will need to use the XmlHttpRequest object, or, even simpler, making an ajax call with jQuery. This object, together with CORS, make possible to make cross domain requests.

The snippet of XmlHttpRequest goes like this:







And the call using jQuery:













XDomainRequest is the response by Microsoft against XmlHttpRequest with CORS protocol, instead of integrate it (CORS) with IExplorer, they create their own object for cross domain's requests.

Regarding CORS, all you have to do, is making your service server aware for OPTIONS verb and return the needed headers, because the browser itself makes the magic happens. So, to enable cross domain ajax call, at server you need to...



















With all this set up, you should have your communication with your server on. One little note, be aware of kind of service and object you are using, for instance, XDomainRequest only accept text/plain to send (xdr.send(string)) and an WCF service accepts XML, JSON, etc. but not text/plain.


References:
http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
http://stackoverflow.com/questions/4739384/xdomainrequest-problem
http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/
http://www.codeproject.com/KB/ajax/jQueryWCFRest.aspx

No comments:

Post a Comment