responding with multiple JSON renders. (Ruby/Rails)

被刻印的时光 ゝ 提交于 2019-12-03 15:00:51

问题


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?


回答1:


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,
      ...

});


来源:https://stackoverflow.com/questions/6995660/responding-with-multiple-json-renders-ruby-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!