Rails 3:如何在Ajax调用中"redirect_to"?

Mis*_*hko 85 ajax redirect ruby-on-rails ruby-on-rails-3

attempt_login提交登录表单后,使用Ajax调用以下方法.

class AccessController < ApplicationController
  [...]
  def attempt_login
    authorized_user = User.authenticate(params[:username], params[:password])

    if authorized_user
      session[:user_id] = authorized_user.id
      session[:username] = authorized_user.username
      flash[:notice] = "Hello #{authorized_user.name}."
      redirect_to(:controller => 'jobs', :action => 'index')
    else
      [...]
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

问题是redirect_to不起作用.

你怎么解决这个问题?

Mis*_*hko 100

最后,我刚刚更换了

redirect_to(:controller => 'jobs', :action => 'index')
Run Code Online (Sandbox Code Playgroud)

有了这个:

render :js => "window.location = '/jobs/index'"
Run Code Online (Sandbox Code Playgroud)

它工作正常!

  • 更好的方法是`render:js =>"window.location ='#{jobs_path}'"` (42认同)
  • 它有效,但是用实际的json成功消息传回重定向位置并在前端重定向会不会更好? (3认同)
  • 真棒.任何人都知道为什么简单的redirect_to不起作用? (2认同)

nat*_*vda 64

有一种非常简单的方法可以为下一个请求保留闪存.在你的控制器做类似的事情

flash[:notice] = 'Your work was awesome! A unicorn is born!'
flash.keep(:notice)
render js: "window.location = '#{root_path}'"
Run Code Online (Sandbox Code Playgroud)

flash.keep将确保闪光灯不停地为下一个请求.因此,当root_path渲染时,它将显示给定的flash消息.Rails太棒了:)

  • 谢谢!关于flash.keep不知道 (3认同)

Mik*_*ike 27

我认为这稍微好一些:

render js: "window.location.pathname='#{jobs_path}'"

  • 略微更好:`render js:"window.location.pathname =#{jobs_path.to_json}"` (12认同)

Pri*_*iit 26

在我的一个应用程序中,我使用JSON来继续重定向和闪存消息数据.它看起来像这样:

class AccessController < ApplicationController
  ...
  def attempt_login
    ...
    if authorized_user
      if request.xhr?
        render :json => {
          :location => url_for(:controller => 'jobs', :action => 'index'),
          :flash => {:notice => "Hello #{authorized_user.name}."}
        }
      else
        redirect_to(:controller => 'jobs', :action => 'index')
      end
    else
      # Render login screen with 422 error code
      render :login, :status => :unprocessable_entity
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

简单的jQuery示例如下:

$.ajax({
  ...
  type: 'json',
  success: functon(data) {
    data = $.parseJSON(data);
    if (data.location) {
      window.location.href = data.location;
    }
    if (data.flash && data.flash.notice) {
      // Maybe display flash message, etc.
    }
  },
  error: function() {
    // If login fails, sending 422 error code sends you here.
  }
})
Run Code Online (Sandbox Code Playgroud)


Yar*_*rin 18

结合最好的答案:

...
if request.xhr?
  flash[:notice] = "Hello #{authorized_user.name}."
  flash.keep(:notice) # Keep flash notice around for the redirect.
  render :js => "window.location = #{jobs_path.to_json}"
else
...
Run Code Online (Sandbox Code Playgroud)