加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何在’format.json / xml {render:json / x

发布时间:2020-12-17 02:51:55 所属栏目:百科 来源:网络整理
导读:我正在使用 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请求时,会设置这些
我正在使用 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

我想添加/设置标头值并添加新参数,如message2或header2.

我该怎么做format.json / xml {render:json / xml => @ user.to_json / xml}语法?

解决方法

format.foo {render …}的东西需要一个块.你可以把你想要的东西放在那里:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读