views:

269

answers:

3

I saw this code in a Rails controller:

respond_to do |format|
  format.js {}

I've seen this for XML and HTML formats but not for Javascript.

Is this the way you specify a return format if you use for REST, like if you use replace_html or remote_form_for? I know RJS templates return compiled Javascript so I'm thinking maybe this is where this code might kick in.

If you put code inside the hash symbols(format.js {}), is that what gets send back as javascript to the browser?

+1  A: 

It is used when an AJAX request is sent from the browser to a controller. The controller can respond with a script (which is generated by ruby statements in the view) which will be executed on the client.

Bruno Ranschaert
+1  A: 

Rails does a little magic on figuring out what 'template' to send out

in controller:
   def foo
   end

in view: (app/views/controller/) you can have 
    foo.html.erb   (usual, html template)
    foo.rjs  (javascript template)

rails will send out the right template back to the browser, HTML for regular requets and RSJ for Ajax requests. You might want to put in javascript code like 'page.replace_html' ..etc in your RJS template. This way, you keep the controller clear of view code.

sujee
A: 

yuo can always just add the format to the url and see what it responds, /something.js would respond using the format.js code, if you want to use it, you can do the following to avoid rendering your entire layout:

format.js { render :layout => false, :text => @models.to_json }

that would respond with a json string

format.js { render :layout => false }

would require a template called [action].js.erb

kristian nissen