Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling jsonp in rails 3 controller

I want my controller action to handle jsonp requests from jquery $.getJSON. In my controller action i have the following respond_to block:

respond_to do |format|
  format.html { render json: {:items_by_tag => @tagged_item_list}}
  if params[:callback]
        format.js { render :json => {:items_by_tag => @tagged_item_list}.to_json, :callback => params[:callback] }
  else
        format.json { render json: {:items_by_tag => @tagged_item_list}}
  end
end

But I'm getting SyntaxError:invalid label when i call the url from $.getJSON. My url is of the form http://myservice.com?param1=a&param2=b&callback=?.
What is the problem with my code which is causing jsonp to fail?

like image 273
jimcgh Avatar asked Jan 02 '13 11:01

jimcgh


People also ask

Can I use JSON in a Rails application?

If your Rails application presents an API that utilizes JSON, it can be used with popular Javascript frameworks as well as any other application that can handle JSON. The JSON serialization process consists of two stages: data preparation and transformation to the JSON format. Data preparation consists of transforming Ruby objects into a hash map.

How does the JSON serialization process work?

The JSON serialization process consists of two stages: data preparation and transformation to the JSON format. Data preparation consists of transforming Ruby objects into a hash map. If you have a Person model and each person has email and name attributes, then data ready for serialization would look like the following:

What is JSON (JavaScript Object Notation)?

JSON (JavaScript Object Notation) is a data format that encodes objects in a string. Such data representation can easily be translated between server and browser but also between server and server.

How to serialize a person model in rails?

If you have a Person model and each person has email and name attributes, then data ready for serialization would look like the following: Notice that in Rails you can call the #to_json method on a model instance. It will return a hash map with all model attributes.


1 Answers

respond_to do |format|
  format.html { render json: {:items_by_tag => @tagged_item_list}}
   if params[:callback]
     format.js { render :json => {:items_by_tag => @tagged_item_list.to_json}, :callback => params[:callback] }
   else
    format.json { render json: {:items_by_tag => @tagged_item_list}}
   end
 end
like image 56
shweta Avatar answered Sep 22 '22 11:09

shweta