Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ajax/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何将代码包含到js.erb视图中?在rails 3中_Ruby On Rails_Ajax_Unobtrusive - Fatal编程技术网

Ruby on rails 如何将代码包含到js.erb视图中?在rails 3中

Ruby on rails 如何将代码包含到js.erb视图中?在rails 3中,ruby-on-rails,ajax,unobtrusive,Ruby On Rails,Ajax,Unobtrusive,我有一个网站使用不引人注目的ajax 简而言之,流程是: 远程链接 由控制器管理的请求 js.erb视图将响应发送回浏览器 我希望我所有的js.erb视图都能执行类似的“维护活动”,比如在需要时插入flash消息、更新url等等 我怎样才能把它弄干?理想情况下,我会使用一个partial,每次都要执行代码,但我找不到如何做到这一点 更新1:示例 我的js.erb文件: $("#challenge_actions").html("<%= escape_javascript(render

我有一个网站使用不引人注目的ajax

简而言之,流程是:

  • 远程链接
  • 由控制器管理的请求
  • js.erb视图将响应发送回浏览器
我希望我所有的js.erb视图都能执行类似的“维护活动”,比如在需要时插入flash消息、更新url等等

我怎样才能把它弄干?理想情况下,我会使用一个partial,每次都要执行代码,但我找不到如何做到这一点

更新1:示例

我的js.erb文件:

$("#challenge_actions").html("<%= escape_javascript(render partial: "challenges/best_practice_button")%>");
$("#flash_messages").html("<div id='flash_notice'><%= escape_javascript(flash[:notice])%></div>");
$(“#挑战行动”).html(“”);
$(“#flash_messages”).html(“”);
如何提取带有flash_消息的行,并将其自动包含在我的所有js.erb文件中


谢谢

您也可以使用erb中的部分模板,假设您想用id“container”替换div的内容,然后假设您使用的是jquery,您可以这样做

$('#container').html('<%= escape_javascript(render(:partial => 'mypartial'))%>')
$('#container').html(''mypartial'))%%>)

您可以使用js布局,就像html布局一样

布局/custom.js.erb

alert("<%=j flash[:notice] %>");
<%= yield %>
def your_action

  flash[:notice] = "hello world"
  @hello = "hello world"

  respond_to do |format|
    format.js { render layout: "custom" }
  end
end
alert("<%= j @hello %>");
你的行动.js.erb

alert("<%=j flash[:notice] %>");
<%= yield %>
def your_action

  flash[:notice] = "hello world"
  @hello = "hello world"

  respond_to do |format|
    format.js { render layout: "custom" }
  end
end
alert("<%= j @hello %>");
警报(“”);

是,但部分文件是否可以是.js.erb文件?请参阅更新1操作,以便首先触发maintenance.js.erb,然后触发您的_action.js.erb?恐怕不行。但这正是我需要的。实际上,类似于before_过滤器的东西。太棒了!非常感谢你!