简体   繁体   English

如何在before_filter中响应ajax调用

[英]how to respond to an ajax call in before_filter

I write a before_filter like this: 我写了一个像这样的before_filter:

def authenticate_user
  if request.xhr?
    flash.now[:alert] = 'Error'
    render :partial => "js_helpers/popover", :formats => :js
  else
    authenticate_user!
  end
end

However, it doesn't work as expected. 但是,它没有按预期工作。 The log file shows: 日志文件显示:

  Rendered js_helpers/_popover.js.erb (0.1ms)
Filter chain halted as :authenticate_user rendered or redirected

The function of the js code is to show a popover block showing flash message. js代码的功能是显示一个显示flash消息的弹出框。 but it looks like the js code is not excited at all. 但看起来js代码根本不是很兴奋。

So, I changed my way: 所以,我改变了方向:

def authenticate_user
  if request.xhr?
    flash.now[:alert] = 'Error'
    render :js => "window.location = '/users/sign_up'"
  else
    authenticate_user!
  end
end

Instead, I want to redirect to sign up page. 相反,我想重定向到注册页面。

However, there is still problems. 但是,仍然存在问题。 the flash seems not work 闪光似乎不起作用

How can I achieve my goal: 我怎样才能实现我的目标:

when the request is an ajax call, execute come javascript code or redirect_to a new page. 当请求是ajax调用时,执行javascript代码或redirect_to新页面。 Under both condition, I need to store some message in flash. 在这两种情况下,我需要在flash中存储一些消息。

Plus, the javascript code is very long so that I need to put it in a file. 另外,javascript代码很长,所以我需要把它放在一个文件中。 How can I use render :js to execute a javascript inside a file? 如何使用render:js在文件中执行javascript?

I think that instead of trying to render javascript code for the client to execute, you should return a json response that your client will understand. 我认为,您应该返回客户端将理解的json响应,而不是尝试为客户端执行javascript代码。

def authenticate_user
  if request.xhr?
    render :json => { alert: 'Error', redirect: sign_up_path }, :status => 403
  else
    authenticate_user!
  end
end

In your ajax calls, trap the 403 status code, display the alert message, and redirect to the given url. 在您的ajax调用中,捕获403状态代码,显示警报消息,并重定向到给定的URL。 You should be able to make this a standard hook for a 403 (or whatever status code seems most appropriate) so that it can be as DRY as the before_filter. 你应该能够将它作为403(或任何状态代码似乎最合适)的标准钩子,以便它可以像before_filter一样干燥。

I think that using rails' built in redirect is what you are looking for. 我认为使用rails'内置重定向是你正在寻找的。

def authenticate_user
  if request.xhr?
    flash[:alert] = 'Error'
    redirect_to user_sign_up
  else
   authenticate_user!
  end
end

This should redirect and fill out the flash message 这应该重定向并填写flash消息

Here's the example from the rails guides 以下是导轨指南中的示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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