rails redirect_to format html在js中发送响应

nde*_*eau 8 html javascript redirect ruby-on-rails

我在我的一些控制器中创建了一个before_filter,用于将关键字搜索重定向到父控制器

这很简单:

  before_filter :redirect_search
  def redirect_search
    redirect_to controller: "buildings", action: "index", format: "html" if params[:q].present?
  end
Run Code Online (Sandbox Code Playgroud)

请注意,keyword_search以"js"格式发送

一切似乎都有效.当我查看服务器时,我可以看到建筑物/索引已运行并且页面已呈现但浏览器中没有任何反应.

在浏览器的控制台中,我看到了这一点

GET http://localhost:3000/buildings.html 200 OK
Run Code Online (Sandbox Code Playgroud)

它在响应正文中有html页面

这意味着buildings/index以html身份运行,但随后以js形式发送到浏览器.

为什么会这样?我该如何解决?

Bac*_*uty 16

试试吧

def redirect_search
     respond_to do |format|
            format.html {redirect_to buildings_path} if params[:q].present?
            format.js {render :js => "window.location.href='"+buildings_path+"'"} if params[:q].present?
     end
end
Run Code Online (Sandbox Code Playgroud)


nde*_*eau 9

感谢Bachan的回答,我可以这样解决我的问题:

  def redirect_search
    render :js => "window.location.href='"+buildings_path+"'" if params[:q].present?
  end
Run Code Online (Sandbox Code Playgroud)

谢谢!

  • 哇,那很难看.Rails中是否缺少某些内容,或者我们是不是以Rails方式开始做事情? (18认同)