我的控制器有一个名为list.html.erb的页面
当用户点击链接时,我想要动态地将内容附加到页面并在之后执行javascript。 是否有可能有一个呈现js.erb文件的方法,并且我将包含内容的变量放入此文件中?
最好的phil
答案 0 :(得分:0)
如上所述:http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to您需要使用
link_to 'Something', 'somewhere', remote: true
答案 1 :(得分:0)
是的,当然。不过,这可能不是最好的行动方案。
如果您通过Javascript增强了视图的功能,那么将代码保存在Javascript而不是Ruby生成的Javascript中可能会更好。
创建一个简单的HTML链接,以JSON格式从控制器获取新内容,甚至是HTML代码段。使用类似$ .ajax及其成功回调函数的方法将所述响应附加到页面中的元素。
$.ajax({
url: "whatever/here",
type: "GET",
data_type: "json",
success: function(response) {
$("#element_in_question").append(response); //if HTML; if JSON, parse and build the HTML
},
error: function(xhr, status, message) {
//indicate failure somehow
}
});
答案 2 :(得分:0)
您可以在list.html.erb中添加部分内容,并在页面list.html.erb上更改部分内容时显示部分内容。例如,考虑到您的list.html.erb文件,您可以在页面中包含以下内容
<form_for :something, :remote => true, :method => get :url => {:action => "partial"} do |f| %>
//write your code here
<%=f.submit%> //here you can have :onchange in the form_for tag if you do not want a submit button
在列表页面中为部分写一个部门,如下所示
<div id="partial">
</div>
写一个这样的partial.js.erb文件:
$('#partial').html("<%=j render "partial" %>");
创建一个_partial.html.erb
文件,其中包含您要动态添加list.html.erb的内容。
在控制器中,添加以下代码:
def partial
//write your code here
respond_to do |format|
format.js
end
这将在列表页面的div标签中显示添加的内容,其中div为“partial”