【问题标题】:How to set headers of a JSON/XML response in 'format.json/xml { render :json/xml => @user.to_json/xml }'?如何在 'format.json/xml { render :json/xml => @user.to_json/xml }' 中设置 JSON/XML 响应的标头?
【发布时间】:2011-02-18 18:13:18
【问题描述】:

我正在使用 Ruby on Rails 3,我正在尝试设置 JSON/XML 响应的值。

在我的控制器中

respond_to do |format|
  format.xml { render :xml => @user.to_xml }
  format.json { render :json => @user.to_json }
end

当我对 JSON/XML 发出 HTTP GET 请求时,它会设置像这样的常用值

header: 
  date: 
  - Fri, 18 Feb 2011 18:02:55 GMT
  server: 
  - Apache ...
  etag: 
  - "\"0dbfd0ec23934921144bd57d383db443\""
  cache-control: 
  - max-age=0, private, must-revalidate
  x-ua-compatible: 
  - IE=Edge
  x-runtime: 
  - "0.033209"
  status: 
  - "200"
  transfer-encoding: 
  - chunked
  content-type: 
  - application/json; charset=utf-8 #or application/xml; charset=utf-8
http_version: "1.1"
message: OK
read: true

我想添加/设置 header 值并添加新参数,例如 message2header2

如何在 format.json/xml { render :json/xml => @user.to_json/xml } 语法中做到这一点?

【问题讨论】:

    标签: ruby-on-rails xml json ruby-on-rails-3 response


    【解决方案1】:

    format.foo { render ... } 东西占用了一个块。你可以放任何你想要的东西:

    format.json do
      response['X-Message-1'] = 'Hello'
      render :json => @user.to_json
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-23
      • 1970-01-01
      • 1970-01-01
      • 2014-02-19
      • 2017-01-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多