views:

37

answers:

1

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.

+2  A: 

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.

Nikita Rybak
But like what do I use the callback for? And do I need to do anything so my server (NGINX) so that it excepts requests from any domain?
Joseph Silvashy
@Joseph I clarified about first question in edit. I don't know anything about NGINX, but normally servers accept all requests from the web. You just need server to return valid javascript code.
Nikita Rybak
the render :json as a :callback parameter so that you don't have to wrap the response by yourself see http://railsapi.com/doc/rails-v2.3.8/classes/ActionController/Base.html#M001802 (ex: render :json => {:name => "David"}.to_json, :callback => 'show')
hellvinz