I’m working on a project now that makes heavy use of XHR (XMLHttpRequest) to load data from a server. I’m writing the HTML/JS portion of the application on my local machine, but my server development environment is on a remote server under a different domain. Typically cross-domain XHR request aren’t allowed due to browser security restrictions, however there are two easy work-arounds:
- Cross-Origin Resource Sharing
<script> tag (script tags are not subject to the same origin policy which is what enables things like ads to be served from different domains). In your request (formed as the
(Note that JSONP requests are probably best handled by robust frameworks like the
I’ve used JSONP in the past for things like this prototype client-side news reader, but the project I’m working on now uses XML as well as JSON, so I decided to use a different approach.
Cross-Origin Resource Sharing
Cross-origin resource sharing is similar to cross-domain policy files in the Flash word, but they are done through HTTP headers. The specification defines several different headers, however the only one I’ve needed so far is the response header
Access-Control-Allow-Origin. Allowing my server to share resources with my local machine was as easy as adding the following line of PHP code before writing to the output buffer:
(Seeker is the name of my development machine, named after the excellent Jack McDevitt novel.)
Of course, once I move the client-side portion of my application (the HTML, JS, and CSS files) to my server, I can delete or comment this line out since the application will be served from the same domain from which it needs to request data. In the meantime, however, it’s made local development much easier.
Cross-origin resource sharing is part of the XMLHttpRequest Level 2 specification, and is supported in all modern browsers.