响应多个 JSON 渲染.(红宝石/轨道) [英] responding with multiple JSON renders. (Ruby/Rails)

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

问题描述

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

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

我试图将多个对象呈现为 json 作为控制器中的响应.所以是这样的:

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 

问题是我只得到一个 json 并且它总是最重要的.有没有办法以这种方式渲染多个对象?

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?

或者我应该创建一个由其他对象组成的新对象.to_json?

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

推荐答案

你实际上可以这样做:

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

如果您使用 jquery,则需要执行以下操作:

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

等等

回答你的问题,你不一定要解析响应,这只是我通常做的.有许多功能可以立即为您完成,例如:

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 渲染.(红宝石/轨道)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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