Loading Data Across Domains with JavaScript

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:

  1. JSONP
  2. Cross-Origin Resource Sharing


JSONP gets around the same origin policy by loading JavaScript from another domain into a dynamically generated <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 src attribute of the script tag), you typically specify a callback function that you have already defined in your application. The JavaScript that gets loaded into the dynamically generated script tag will call the specified function, passing in the requested JSON data.

(Note that JSONP requests are probably best handled by robust frameworks like the jQuery.getJSON() function.)

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:

header('Access-Control-Allow-Origin: http://seeker.home');

(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.

Comments are closed.