How to respond to HTML requests made through AJAX in Rails

I am trying to write a Rails controller method that will respond to requests made both "normally" (for example, by reference) and through ajax.

Normal case: the controller should respond with fully-formed HTML using a layout.

Ajax case: the compiler should respond with the HTML fragment generated by the template (no layout)

Here's the jQuery code that I created to execute on the client side in order to fulfill the receive request.

jQuery.get("http://mydomain.com/some_controller/some_action", 
           {}, 
           function(data, textstatus) {
             jQuery("#target").html(data);
           },
           "html");

What is the best way to handle this in Rails?

+5
source share
4 answers

Your controller dynamically selects whether to use a layout based on request.xhr?.

:

class SomeController < ApplicationController
  layout :get_layout

  protected

  def get_layout
    request.xhr? ? nil : 'normal_layout'
  end
end
+13

:

   respond_to do |format|
      format.js if request.xhr?
      format.html { redirect_to :action => "index"}
    end
+9

URL-.

config/initializers/mime_types.rb:

Mime::Type.register_alias 'text/html', :xhtml

some_controller/some_action.xhml.haml.

URL: http://mydomain.com/some_controller/some_action.xhtml, , ,

url_for(:controller => :some_controller, :action => :some_action, :format => :xhtml)

, , ( ):

some_controller_some_action_imaginary_path(:format => :xhtml)

, respond_to .

, , , - , ajax- , , , .


EDIT:
jQuery 1.5.1 mime $.ajax():

mimeType : mime type to override XMR tim.

This may be an alternative to the explicit format in the urls, although I have not tried it yet.

+3
source

If you are using a new version of rails, you can simply add .js to the path and it will conclude that the request is a JavaScript call

0
source

All Articles