我有一个看起来像这样的行动
:layout=>false
我的目的是返回一个json数据,并且还想执行render :json => @next_level
。有没有办法通过一个动作实现这一目标?
当我单独给asset_map_fullscreen.html.erb
时,它只是在我的页面中呈现json数据而没有别的。
我也有一个{{1}}文件。我想渲染此文件以及发送json响应(我需要json数据来执行某些操作)。
答案 0 :(得分:2)
我想渲染此文件以及发送json响应(我需要json数据来执行某些操作。)
TL; DR:由于http原型规范,这是不可能的。一个人应该做两个单独的请求。
完成任务的最简单方法是呈现html
(通过erb
或其他),然后调用另一个控制器操作(例如,asset_map_fullscreen_json
)从呈现的页面使用javascript / AJAX。另一方面,您可以使用相同的端点(同时仍然将主请求和后续的AJAX调用分开):
respond_to do |format|
format.html { render layout: false } # or whatever to simply render html
format.json { render json: @next_level.to_json }
end
答案 1 :(得分:1)
如果你只需要渲染json而不是像这样。
render :json => @next_level
如果你想渲染一些html文件就像
那样render partial: 'asset_map_fullscreen'
你要同时渲染两者。这是不可能的 。可能的解决方案是
render partial: 'asset_map_fullscreen', data: @next_level
通过这个你可以访问部分变量。您应该部分地进行必要的计算。
还有另一种可能性,即使用操作名称创建js文件,并在该文件中执行检查。为此,请查看@ 7urkm3n回答
最后一个解决方案是将它们保存在部分隐藏文件中,然后使用javascript从html中提取它。
答案 2 :(得分:1)
不确定我是否理解正确,但如果你想渲染asset_map_fullscreen.html.erb
模板但在页面中也需要json(出于某种原因,比如操纵数据或其他),你可以只渲染模板和将json作为可在视图文件中使用的实例变量传递:
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
@next_level_json = process_relationship.to_json
render :asset_map_fullscreen
end
然后在视图代码中,您可以引用@next_level_json
,这样您就可以将@next_level
保留为常规对象。不确定process_relationship
来自哪里(控制器上的方法?)
明白你只能返回一种Content-Type
类型的Set
,它可以是json,html,xml,binary,无论你想要什么,但一次只能做一件事。如果您需要显示一个html页面并将其呈现给浏览器然后传递json,那么您只需将模板呈现为html(如上所述)并将json数据保存在实例变量中以在视图中使用。你根本无法在同一个响应中返回html和json(如在xhr / ajax请求中)。
答案 3 :(得分:0)
respond_to do |format|
format.json { render :layout => false, :data => @next_level.to_json }
end
或简单
render json: @next_level
希望这对您有用
答案 4 :(得分:0)
您在渲染中缺少逗号。大多数情况下,如果渲染JSON,则不需要layout
,它最好只使用HTML。
<强>已更新强>
当你这样打电话时,你得到了对象,所有你必须在以后的任何地方将它附加到那个页面。
JS档案:
创建asset_map_fullscreen.js.erb
文件,在页面中添加此文件。
console.log('yeah worked to test only');
console.log(<%= j render @next_level %>);
控制器:
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
respond_to do |format|
format.js {}
end
end
现在您需要将remote: true
添加到按钮或form_for,无论如何。
如果您发布,我可以帮助您。
答案 5 :(得分:0)
简单地说:render :json => @next_level
有效