Rails detect if request was AJAX

前端 未结 5 893
悲&欢浪女
悲&欢浪女 2020-11-28 04:21

In my action I wish to only respond with processing if it was called from an AJAX request. How do I check?

I want to do something like this:

def acti         


        
相关标签:
5条回答
  • 2020-11-28 05:04
    request.xhr? 
    

    if this return 0 then it means its an ajax request, else it will return nil

    0 讨论(0)
  • 2020-11-28 05:11

    If you're using :remote => true in your links or forms, you'd do:

    respond_to do |format|
      format.js { #Do some stuff }
    

    You can also check before the respond_to block by calling request.xhr?.

    0 讨论(0)
  • 2020-11-28 05:13

    You can check for a header[X-Requested-With] to see if it is an AJAX request. Here is a good article on how to do it.

    Here is an example:

    if request.xhr?
      # respond to Ajax request
    else
      # respond to normal request
    end
    
    0 讨论(0)
  • 2020-11-28 05:13

    I like using before_action filters. They are especially nice when you need the same filter/authorization for multiple actions.

    class MyController < AuthController
      before_action :require_xhr_request, only: [:action, :action_2]
    
      def action
        @model = Model.find(params[:id])
      end
    
      def action_2
        # load resource(s)
      end
    
      private
    
      def require_xhr_request
        redirect_to(root_url) unless request.xhr?
      end
    end
    
    0 讨论(0)
  • 2020-11-28 05:18

    The docs say that request.xhr?

    Returns true if the “X-Requested-With” header contains “XMLHttpRequest”....
    

    But BEWARE that

    request.xhr? 
    

    returns numeric or nil values not BOOLEAN values as the docs say, in accordance with =~.

    irb(main):004:0> /hay/ =~ 'haystack'
    => 0
    irb(main):006:0> /stack/ =~ 'haystack'
    => 3
    irb(main):005:0> /asfd/ =~ 'haystack'
    => nil
    

    It's based on this:

    # File actionpack/lib/action_dispatch/http/request.rb, line 220
    def xml_http_request?
      @env['HTTP_X_REQUESTED_WITH'] =~ /XMLHttpRequest/
    end
    

    so

    env['HTTP_X_REQUESTED_WITH'] =~ /XMLHttpRequest/  => 0
    

    The docs:

    http://apidock.com/rails/v4.2.1/ActionDispatch/Request/xml_http_request%3F

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