Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding the basics of JSONP and Rails

I'm having a tough time finding some basic information on the accepted way to do JSONP with my app...

Let me explain, say I have an app (App A) that provides a response in json, how can I call that script using jQuery from a different site, and load that JSON data? I'm pretty sure I can just link to a JS file on app A and use that to load the data into the page, but other than that I'm a little lost on the proper convention of doing this... any help is seriously greatly appreciated, even just pointing me in the right direction or article would be awesome.

like image 971
JP Silvashy Avatar asked Aug 25 '10 03:08

JP Silvashy


1 Answers

It's really quite trivial.

On client side, you do usual ajax request, just with 'jsonp' type.

$.ajax({
    dataType: 'jsonp',
    success: function(response) {
    }
});

On the server side, you return data like this

'/**/' + params[:callback] + '("' + response + '");';

It will produce something like /**/callback_name("my_response");. my_response string will be passed to ajax success handler by jquery.

You can also return json objects and arrays too, like callback_name([1, 2, 3]);

edit
The flow will go like this.

  1. jquery sends ajax request and provides callback parameter automatically.
  2. Your server writes valid javascript code as response.
  3. Browser executes returned javascript code. If it invokes callback function, jquery returns to you parameter passed in callback function.

There's also a wikipedia article, if have confusion on what jsonp is.

2015 edit Note that Rails changed the way that they do this, due to a security vulnerability. They are pre-pending the function call with a JavaScript comment, which I added to the code above. This is the code change in question.

like image 165
Nikita Rybak Avatar answered Oct 28 '22 19:10

Nikita Rybak