Ruby-on-rails Rails 检测请求是否为 AJAX
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8220701/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails detect if request was AJAX
提问by Razor Storm
In my action I wish to only respond with processing if it was called from an AJAX request. How do I check?
在我的操作中,如果它是从 AJAX 请求调用的,我希望只响应处理。我如何检查?
I want to do something like this:
我想做这样的事情:
def action
@model = Model.find(params[:id])
respond_to do |format|
if (wasAJAXRequest()) #How do I do this?
format.html #action.html.erb
else
format.html {redirect_to root_url}
end
end
回答by Amir Raminfar
回答by Sean Hill
If you're using :remote => truein your links or forms, you'd do:
如果你:remote => true在你的链接或表单中使用,你会这样做:
respond_to do |format|
format.js { #Do some stuff }
You can also check before the respond_to block by calling request.xhr?.
您还可以通过调用在 respond_to 块之前进行检查request.xhr?。
回答by pixelearth
The docs say that request.xhr?
文档说 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 =~.
根据=~,返回数字或 nil 值,而不是文档所说的 BOOLEAN 值。
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
http://apidock.com/rails/v4.2.1/ActionDispatch/Request/xml_http_request%3F
回答by HarlemSquirrel
I like using before_actionfilters. They are especially nice when you need the same filter/authorization for multiple actions.
我喜欢使用before_action过滤器。当您需要对多个操作使用相同的过滤器/授权时,它们特别好。
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
回答by vidur punj
request.xhr?
if this return 0 then it means its an ajax request, else it will return nil
如果返回 0 则表示它是一个 ajax 请求,否则返回 nil

