简体   繁体   English

Rails-如何在HTML响应中呈现js

[英]Rails - How to render js in an html response

I have an action 'index', that when called via ajax, renders index.js which renders a partial: 我有一个动作“索引”,当通过ajax调用时,将呈现index.js,从而呈现部分内容:

$("#content").html("<%= escape_javascript(render :partial => 'index') %>");

How do I make the same thing happen in the html response? 我如何使html响应中发生相同的事情? I tried: 我试过了:

format.html { render "index.js" }

And although I don't get any errors, the js code doesn't seem to run, because the partial doesn't render. 尽管我没有收到任何错误,但js代码似乎没有运行,因为未渲染部分代码。

Have you tried wrapping the script inside <script> tag? 您是否尝试过将脚本包装在<script>标记内?

Your index.html.erb would look like this: 您的index.html.erb如下所示:

<script type="text/javascript">
  $("#content").html("<%= escape_javascript(render :partial => 'index') %>");
</script>

The default render is a shortcut for render :action => :action_name . 默认渲染是render :action => :action_name的快捷方式。 To specify a filesystem path use render :file => "index.js" 要指定文件系统路径,请使用render :file => "index.js"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM