我有一个 Controller “UserController”,它应该响应对 http://localhost:3000/user/3
的正常请求和 ajax 请求。
当是正常请求时,我要渲染我的 View 。当是AJAX请求时,我想返回JSON。
正确的方法似乎是 respond_to do |format|
block 。编写 JSON 很容易,但我怎样才能让它响应 HTML 并像往常一样简单地呈现 View 呢?
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
最佳答案
据我所知,没有必要在 format.html 中“渲染显示”,它将自动为 ex 寻找相应的操作 View :show.html.erb 用于 html 请求,show,js,erb 用于 JS 请求。
这样就可以了
respond_to do |format|
format.html # show.html.erb
format.json { render json: @user }
end
此外,您可以通过检查request.xhr 来检查请求是否为ajax?如果请求是 ajax 请求,它返回 true。
关于ruby-on-rails - rails : respond_to JSON and HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20188047/