Rails detect if request was AJAX

前端 未结 5 966
悲&欢浪女
悲&欢浪女 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: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

提交回复
热议问题