JSONP with Rails
-
19-09-2019 - |
Question
I'm trying to retrieve JSON data from a remote site with Rails/Prototype.
I've found that there's a branch of Prototype that has an Ajax.JSONRequest()
function. I can't get this to work.
jQuery has a $.getJSON()
function, but I'm using some Prototype functions and I'd rather not switch to jQuery or use no conflict mode.
What am I missing? It seems like this would be easily done with Rails or Prototype.
Solution
Do you need to use Rails helpers to make the client request JSON? It's easy with Prototype
new Ajax.Request('/some_url', {
method:'get',
onSuccess: function(transport){
var json = transport.responseText.evalJSON();
}
});
You just need to make sure that /some_url responds with JSON to an XHTTPRequest (preferably using respond_to?, but you can also check request.xhr?), using Rails' Object#to_json method.
OTHER TIPS
You can also use the JSONP rack middlware that's available in rack-contrib. This gives you the ability to just append &callback=method to your query string and have the response from rails wrapped in your callback method.
Just add this to your application.rb:
require "rack/contrib/jsonp"
class Application < Rails::Application
config.middleware.use Rack::JSONP
end
nothing built into rails specifically for jsonp, but there's a couple things that you could do if you wanted your rails app to play nice with jsonp.
- create a jsonp mime-type in config/initializers/mime_types.rb
- extend object with a to_jsonp method that will wrap calls to json in your passed callback. something like:
def to_jsonp(callback, options={}) "#{callback}(#{self.to_json(options)})" end
- follow this guys article.
http://blogs.sitepoint.com/2006/10/05/json-p-output-with-rails/