[英]Rails: respond_to JSON and HTML
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
正常和 ajax 请求。
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|
正确的做法似乎是
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?
编写 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
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?另外,您可以通过检查 request.xhr 来检查请求是否为 ajax? it returns true if request is a ajax one.
如果请求是 ajax 请求,则返回 true。
Yes, you can change it to是的,您可以将其更改为
respond_to do |format|
format.html
format.json { render json: @user }
end
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_to
work for all the actions in the controller using respond_with :或者使用
respond_to
使respond_to
适用于控制器中的所有动作:
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 responder
to be able to use respond_with.从 Rails 4.2 版本开始,您将需要使用
gem responder
才能使用 respond_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.如果您需要更多控制并希望能够有一些行为不同的动作,请始终使用完整的 respond_to 块。 You can read more here .
您可以在此处阅读更多内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.