rails redirect_to 格式 html 在 js 中发送响应
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18629811/
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 redirect_to format html sends response in js
提问by ndemoreau
I made a before_filter in some of my controller to redirect keyword searches to the parent controller
我在我的一些控制器中做了一个 before_filter 来将关键字搜索重定向到父控制器
It's very simple:
这很简单:
before_filter :redirect_search
def redirect_search
redirect_to controller: "buildings", action: "index", format: "html" if params[:q].present?
end
Please note that the keyword_search is sent in "js" format
请注意,keyword_search 以“js”格式发送
Everything seems to work. When I look at the server, I can see that the buildings/index is run and that the page is rendered but nothing happens in the browser.
一切似乎都有效。当我查看服务器时,我可以看到建筑物/索引已运行并且页面已呈现,但浏览器中没有任何反应。
In the browser's console I see this
在浏览器的控制台中,我看到了这个
GET http://localhost:3000/buildings.html 200 OK
It has the html page in the response body
它在响应正文中有 html 页面
This means that buildings/index is run as html but then sent as js to the browser.
这意味着建筑物/索引作为 html 运行,然后作为 js 发送到浏览器。
Why is that so? How can I fix it?
为什么呢?我该如何解决?
回答by Bachan Smruty
Try with
试试
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
回答by ndemoreau
Thanks to Bachan's answer, I could solve my issue this way:
感谢 Bachan 的回答,我可以这样解决我的问题:
def redirect_search
render :js => "window.location.href='"+buildings_path+"'" if params[:q].present?
end
Thanks!
谢谢!
回答by rhernando
I think the problem is in the view which is doing the request
我认为问题在于正在执行请求的视图
you are sending a JS request (ajax), so you should return a js.erb file and render new HTML using js
您正在发送一个 JS 请求(ajax),因此您应该返回一个 js.erb 文件并使用 js 呈现新的 HTML