Ruby-on-rails Rails:响应 JSON 和 HTML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20188047/
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: respond_to JSON and HTML
提问by Don P
I have a controller "UserController" that should respond to normal and ajax requests to http://localhost:3000/user/3.
我有一个控制器“UserController”,它应该响应对http://localhost:3000/user/3.
When it is a normal request, I want to render my view. When it is an AJAX request, I want to return JSON.
当它是正常请求时,我想呈现我的视图。当是 AJAX 请求时,我想返回 JSON。
The correct approach seems to be a respond_to do |format|block. Writing the JSON is easy, but how can I get it to respond to the HTML and simply render the view as usual?
正确的做法似乎是respond_to do |format|块。编写 JSON 很容易,但是如何让它响应 HTML 并像往常一样简单地呈现视图?
def show
@user = User.find(params[:id])
respond_to do |format|
format.html {
render :show ????this seems unnecessary. Can it be eliminated???
}
format.json {
render json: @user
}
end
end
回答by Amitkumar Jha
As per my knowledge its not necessary to "render show" in format.html it will automatically look for a respective action view for ex : show.html.erb for html request and show,js,erb for JS request.
据我所知,它没有必要在 format.html 中“呈现显示”,它会自动寻找相应的动作视图,例如:show.html.erb 用于 html 请求,show,js,erb 用于 JS 请求。
so this will work
所以这会起作用
respond_to do |format|
format.html # show.html.erb
format.json { render json: @user }
end
also, you can check the request is ajax or not by checking request.xhr? it returns true if request is a ajax one.
另外,您可以通过检查 request.xhr 来检查请求是否为 ajax?如果请求是 ajax 请求,则返回 true。
回答by Santhosh
Yes, you can change it to
是的,您可以将其更改为
respond_to do |format|
format.html
format.json { render json: @user }
end
回答by Nesha Zoric
The best way to do this is just like Amitkumar Jha said, but if you need a simple and quick way to render your objects, you can also use this "shortcut":
最好的方法就像 Amitkumar Jha 所说的那样,但是如果您需要一种简单快捷的方式来渲染您的对象,您也可以使用这个“快捷方式”:
def index
@users = User.all
respond_to :html, :json, :xml
end
Or make respond_towork for all the actions in the controller using respond_with :
或者respond_to使用 respond_with 为控制器中的所有动作工作:
class UserController < ApplicationController
respond_to :html, :json, :xml
def index
@users = User.all
respond_with(@users)
end
end
Starting from Rails 4.2 version you will need to use gem responderto be able to use respond_with.
从 Rails 4.2 版本开始,您需要gem responder使用 response_with 才能使用。
If you need more control and want to be able to have a few actions that act differently, always use a full respond_to block. You can read more here.
如果您需要更多控制并希望能够有一些行为不同的动作,请始终使用完整的 respond_to 块。您可以在此处阅读更多内容。

