简体   繁体   English

Rails 3.1:使用HTML响应json请求

[英]Rails 3.1: respond_to json request with HTML

Is it possible to respond a json request with html instead of json? 是否可以用html而不是json响应json请求?

I would like to do this: 我想这样做:

respond_to do |format|
  format.html { render 'page' }
  format.json { render 'page' } #render an html page instead of a JSON response
end

but Rails will search for a 'page.json' and will throw an error. 但是Rails会搜索'page.json'并抛出错误。

You need to explicitly set format, content-type (default is application/json ) and layout (default is none): 您需要显式设置格式,内​​容类型(默认为application/json )和布局(默认为none):

respond_to do |format|
  format.html { render 'page' }
  format.json do              # render an html page instead of a JSON response
    render 'page.html', {
      :content_type => 'text/html',
      :layout       => 'application'
    }
  end
end

Just use the full filename. 只需使用完整的文件名。 render 'page.html' (or whatever the file is called). render 'page.html' (或任何文件被调用)。

Note that while this should work, if you're doing this, you're probably doing something wrong. 请注意,虽然这应该有效,但如果你这样做,你可能做错了。 Think about how you can restructure your code so you don't have to bend the rules. 考虑如何重构代码,这样您就不必弯曲规则。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM