简体   繁体   中英

Rails 3.1: respond_to json request with HTML

Is it possible to respond a json request with html instead of 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.

You need to explicitly set format, content-type (default is application/json ) and layout (default is 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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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