Ruby on Rails:在一个动作中一起渲染json和布局 [英] Ruby on Rails: Rendering json and layout together in an action

查看:41
本文介绍了Ruby on Rails:在一个动作中一起渲染json和布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似这样的动作

I have an action that looks like this

def asset_map_fullscreen
      @config_items = @config_item.ci_relationships.find(:all, include: [:secondary, :relationship])
      @config_items_associated = @config_item.reverse_ci_relationships.find(:all, include: [:primary, :relationship])

      @next_level = process_relationship
      render :json => @next_level :layout=>false
  end

我的目的是返回json数据,并且还想执行:layout=>false.有一种方法可以通过一个动作来实现这一目标吗?

My purpose is to return a json data and also want to execute :layout=>false . Is there a way to achieve this with a single action ?

当我单独给出render :json => @next_level时,它只是在页面中呈现json数据,而没有其他内容.

When I give render :json => @next_level alone , it's just rendering the json data in my page and nothing else.

我也有一个asset_map_fullscreen.html.erb文件.我想与发送json响应一起呈现此文件(我需要json数据执行一些操作).

I have a asset_map_fullscreen.html.erb file also. I want to render this file along with the sending a json response ( i need the json data to do some actions ).

推荐答案

我想在发送json响应的同时呈现此文件(我需要json数据执行一些操作.)

I want to render this file along with the sending a json response (I need the json data to do some actions.)

TL; DR:由于http原始规范,这是不可能的.一个人应该做两个单独的请求.

TL;DR: This is not possible due to http proto specs. One should do two separate requests.

完成任务的最简单方法是渲染html(通过erb或其他方式),然后使用javascript/AJAX调用另一个控制器动作(例如,asset_map_fullscreen_json).页面已呈现.另一方面,您可以使用相同的端点(同时仍将主请求和后续的AJAX调用分开):

The easiest way to accomplish your task is to render html (via erb or whatever,) then call another controller action (say, asset_map_fullscreen_json) using javascript/AJAX from the page rendered. On the other hand, you might use the same endpoint (while still separating main request and subsequent AJAX call):

respond_to do |format|
   format.html { render layout: false } # or whatever to simply render html
   format.json { render json: @next_level.to_json }
end

这篇关于Ruby on Rails:在一个动作中一起渲染json和布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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