How to respond to HTML requests made via AJAX in Rails

后端 未结 4 378
一生所求
一生所求 2021-02-03 15:12

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

Normal Case: The controller

相关标签:
4条回答
  • 2021-02-03 15:51

    In your controller method, simply do this:

       respond_to do |format|
          format.js if request.xhr?
          format.html { redirect_to :action => "index"}
        end
    
    0 讨论(0)
  • 2021-02-03 16:00

    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
    
    0 讨论(0)
  • 2021-02-03 16:09

    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.

    0 讨论(0)
  • 2021-02-03 16:10

    If you're using a new version of rails you can just append .js onto the path and it will infer that the request is a JavaScript call

    0 讨论(0)
提交回复
热议问题