Tuesday, November 10, 2009

JSON and cross site scripting

Been doing quite a lot of JSON work recently.

Have hit the odd occasion where I've needed to get JSON data across domain boundaries.

To do this, the only way seems to be to make use of <script> tags rather than making use of simple (e.g. Jquery) xml/http get's.

Basically what you do is:

1. Define a callback method, e.g.:

function myCallback(data)
{
// do stuff
}

2. On the server, instead of returning JSON, return the JSON inside a callback call, e.g.:
myCallback({ "thing": 12 });

3. To make the ajax call, then add a script tag to the document head:
            var scriptBlock = document.createElement('script');
            scriptBlock.src = jsonUrlToCall;
            scriptBlock.type = 'text/javascript';
            document.getElementsByTagName('head')[0].appendChild(scriptBlock);

4. Actually, that's it!

No comments:

Post a Comment