responding with multiple JSON renders. (Ruby/Rails)

后端 未结 1 1613
醉话见心
醉话见心 2021-02-06 15:40

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:

相关标签:
1条回答
  • 2021-02-06 16:43

    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,
          ...
    
    });
    
    0 讨论(0)
提交回复
热议问题