jQuery, .getJSON and the Same-Origin Policy

When creating a simple mash-up with data from external sources, you usually want to read the data in a suitable format – such as JSON. The tool for the job tends to be javascript, running in your favourite browser. The only problem is that requests made with XHR (XMLHttpRequest) has to follow the same origin policy, meaning that the request cannot be made for a resource living on another host than the host serving the original request.

To get around this clients usually use JSONP – or a simple modification of the usual JSON output. The data is still JSON, but the output also includes a simple callback at the end of the request, triggering a javascript in the local browser. This way the creator of the data actually tells the browser (in so many hacky ways) that it’s OK, I’ve actually thought this through. Help yourself.

In jQuery you can trigger the usual handling of events by using “?” as the name of your callback function. jQuery will handle this transparently and then trigger the function you provided to .getJSON in the first place.

Example

url = "http://feeds.delicious.com/v2/json/recent?callback=?";

$.getJSON(url, function(data) { alert(data); });

There’s an article up at IBM’s developerWorks giving quite a few more examples and information about the issue.

5 thoughts on “jQuery, .getJSON and the Same-Origin Policy”

  1. Thank you for the detailed info. I have been spending hours today looking into this and this was the perfect answer. Thank you very much!

  2. it says “Unexpected token <" why do i see this error. its cause it sees data as json but its html text plain?

  3. @ali: Yes, that’s because you’re not serving JSON (usually caused by HTML output or an error message on the server side). Use the developer console in your browser to see the actual request performed and the result of that request.

Leave a Reply

Your email address will not be published. Required fields are marked *