Very basic JSONP

JSONP allows you to make HTTP requests outside of your own domain due to the SCRIPT tag not having the same-domain limitation XMLHttpRequest does. The basic form of this workaround is as follows:

var scr = document.createElement('script');
scr.src = 'http://openexchangerates.org/latest.json?callback=formatCurrency';
document.body.appendChild(scr);

function formatCurrency(data) {
	// Do stuff with the data that's been returned.
	1;
}

Lines 1 – 3 of the above create a SCRIPT tag in the DOM, defines the URL to retrieve data from and in line 3 makes the request. To continue the execution cycle, the script at openexchangerates.org must wrap its data in a function:

formatCurrency({ "hello" : "Hi, I'm JSON. Who are you?"})

This calls the locally defined function formatCurrency(), which does whatever it needs to do with the returned data. A quick hack to make your API (assuming you control it) work with JSONP would be as follows:

// assume $json holds the JSON response
if ($GET['callback'] != '') $json = $GET['callback']."( $json )";
return $json;

I have yet to test this, but I imagine you could also be much more daring and avoid having to get the following code uploaded to your API of choice. To do this, execute the first bit of JavaScript on this page, and then execute an eval() statement on the data in the manner of the below:

eval('formatCurrency(' + returned_data + ')');

Leave a Reply

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