响应多个JSON渲染。 (Ruby / Rails) [英] responding with multiple JSON renders. (Ruby/Rails)

查看:168
本文介绍了响应多个JSON渲染。 (Ruby / Rails)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个相对简单的,我很确定它的只是语法。



我试图渲染多个对象作为一个控制器中的响应作为json。这样的东西:

  def info 
@allWebsites = Website.all
@allPages = all
@allElementTypes = ElementType.all
@allElementData = ElementData.all


respond_to do | format |
format.json {render:json => @allWebsites}
format.json {render:json => @allPages}
format.json {render:json => @allElementTypes}
format.json {render:json => ; @allElementData}
end
end
end

我只得到一个单一的json回来,它总是顶部。有没有办法以这种方式呈现多个对象?



还是应该创建一个由其他objects.to_json组成的新对象?


<你可以这样做:

 格式。 json {
render:json => {
:websites => @allWebsites,
:pages => @allPages,
:element_types => @AllElementTypes,
:element_data => @AllElementData
}
}

如果你使用jquery,你将需要做类似的操作:

  data = $ .parseJSON(xhr.responseText); 
data.websites#=> @allWebsites您的控制器中的数据
data.pages#=>来自您的控制器的@allPages数据

等等。



编辑:



回答您的问题,您不一定要解析响应,这只是我通常做的。有很多函数可以立即为你做,例如:

  $。getJSON('/ info',function (data){
var websites = data.websites,
pages = data.pages,
...

});


This is a relatively simple one and I'm pretty sure its just syntax.

Im trying to render multiple objects as json as a response in a controller. So something like this:

  def info
    @allWebsites = Website.all
    @allPages = Page.all
    @allElementTypes = ElementType.all
    @allElementData = ElementData.all


    respond_to do |format|
      format.json{render :json => @allWebsites}
      format.json{render :json =>@allPages}  
      format.json{render :json =>@allElementTypes}  
      format.json{render :json =>@allElementData}
      end
    end
  end 

Problem is I'm only getting a single json back and its always the top one. Is there any way to render multiple objects this way?

Or should I create a new object made up of other objects.to_json?

解决方案

you could actually do it like so:

format.json {
   render :json => {
      :websites => @allWebsites,
      :pages => @allPages,
      :element_types => @AllElementTypes,
      :element_data => @AllElementData
   }
}

in case you use jquery you will need to do something like:

data = $.parseJSON( xhr.responseText );
data.websites #=> @allWebsites data from your controller
data.pages #=> @allPages data from your controller

and so on

EDIT:

answering your question, you don't necessarily have to parse the response, it's just what I usually do. There's a number of functions that do it for you right away, for example:

$.getJSON('/info', function(data) {
  var websites = data.websites,
      pages = data.pages,
      ...

});

这篇关于响应多个JSON渲染。 (Ruby / Rails)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆