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.
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.
callback
parameter automatically.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With