新手问题 Rails 如何直接返回 json 数据

kgra · 2014年08月18日 · 最后由 ericguo 回复于 2014年08月21日 · 4379 次阅读

代码如下

<% test = {"xx"=>"oo"}%>
<%= test.to_json %>

客户端接收到的 http 响应如下:

<!DOCTYPE html>
<html>
<head>
  <title>xxoo</title>

</head>
<body>



{&quot;xx&quot;:&quot;oo&quot;}



</body>
</html>

我想要纯纯的 json 数据,怎么搞?看 guide 里面,说是要想下面这样,

render json: test

我尝试了,不行呀,报错

You invoked render but did not give any of :partial, :template, :inline, :file, :plain, :text or :body option.

环境 ruby 2.0.0p451 (2014-02-24) [i386-mingw32] Rails 4.1.0

render json: {test: 1}

#1 楼 @heimirror 还是不行呀,还是相同的错误 You invoked render but did not give any of :partial, :template, :inline, :file, :plain, :text or :body option

#1 楼 @heimirror 已解决 我在 view 中写的,直接写到 controlloer 中就可以了

应该用 jbuilder gem,这样才是 rails 的推荐做法。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号