XMLHttpRequest method is an important part of any AJAX enabled website. But if you ever try to get data from a web-service that is hosted on a different server using XmlHttpRequest, you will quickly learn that this will not work.
For the longest time, I just knew that this would not work, but I could not give a specific reason as to why this was the case. Finally, I decided to spend a little time and learn the why behind this restriction and here is the answer:
Basically it is because of what is known as the “Same Origin Policy” and its a policy that is enforced by the browser which do it because of a W3C standard for XmlHttpRequest. (“The XMLHttpRequest object can be used by scripts to programmatically connect to their originating server via HTTP”)
There is a lot more in-depth information available on this issue from the Mozilla developer site: https://developer.mozilla.org/En/Same_origin_policy_for_JavaScript. This page also talks about what constitutes a cross domain request.
So are there ways around this: the answer is Yes. But some are more hacky then others and the best solution is dependent on your specific circumstance. (example: http://www.nathanm.com/ajax-bypassing-xmlhttprequest-cross-domain-restriction/)
The solutions that I lean towards are: If the web-service can return a special JSON object called JSONP object – then this is probably the easiest solution. A lot of publicly consumable web-services today expose this format. But what if the returned data is XML or cannot be converted to JSONP? In this case the next best solution is to write server side code that acts as a proxy to the original web-service. Your javascript code, calls a web-service on your server, which in turn calls the original web-service. Obviously for this to work you need to be able to write server side code (PHP or WCF, etc…)
Now you know!
More info:
Same Origin Policy: http://en.wikipedia.org/wiki/Same_origin_policy
JSONP: http://en.wikipedia.org/wiki/JSON#JSONP
Ajaxian: JSONP: JSON With Padding
Inside RIA - What in the heck is JSONP and why would you use it?
No comments:
Post a Comment