Search code examples
jqueryruby-on-railsjsonprototypejsjsonp

JSONP with Rails


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.