Thursday, May 13, 2010

Cross-Domain AJAX with Jquery and JSONP

I've had a heck of a time recently doing some cross-domain ajax scripting with json. This is for an iPhone website and it's basic HTML (no PHP) and it needs to access some data from a specific website. At first we tried, but to no avail.

Eventually we realized that we would need to use JSONP. JSONP requires you to do things on the client side as well as the server side. We use CakePHP here at rain, so you will see that in the server code.

On the client side, as far as I can tell, POST is not an option, so use .getJSON instead

This is the client side code:
var data = $("form").serialize();
$.getJSON("", data, function(data) {

Here is the server side:
echo $this->params['url']['callback'] . '(' . json_encode($data) . ');';

Two helpful articles on the subject:

No comments:

Post a Comment