简体   繁体   中英

How to respond to HTML requests made via AJAX in Rails

I'm trying to write a Rails controller method that will respond to get requests made both "normally" (eg following a link) and via ajax.

Normal Case: The controller should respond with fully decorated HTML using the layout.

Ajax Case: The conroller should respond with the HTML snippet generated by the template (no layout)

Here's the jQuery code, I've created to run on the client side to do the get request.

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

What's the best way to handle this in Rails?

In your controller dynamically select whether to use a layout based on request.xhr? .

For example:

class SomeController < ApplicationController
  layout :get_layout

  protected

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

In your controller method, simply do this:

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

Another way of doing this would be to register new format and specify it explicitly in urls.

Put this in config/initializers/mime_types.rb :

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

Save your template in some_controller/some_action.xhml.haml .

And add format to url: http://mydomain.com/some_controller/some_action.xhtml , or, better, use

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

or, even better, path helpers (if you are restful enough):

some_controller_some_action_imaginary_path(:format => :xhtml)

Mind, that no explicit respond_to dispatching is required for this to work.

This technique might be an overkill if all you want is toggle layout for the same template, but if normal and ajax versions are different, then it is certainly a way to go.


EDIT:
The just released jQuery 1.5.1 brings the option to specify mime type in $.ajax() :

mimeType : A mime type to override the XHR mime type.

This may be an alternative to explicit format in urls, though I haven't tried it yet.

如果您使用的是新版本的rails,您只需将.js附加到路径上,它就会推断该请求是一个JavaScript调用

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM