我有一个名为list.html.erb的页面的控制器如何在rails中动态添加内容?
当用户点击一个链接我想动态地将内容追加到页面并在之后执行JavaScript。 是否有可能有一个呈现js.erb文件的方法,并将包含内容的变量放入此文件中?
最好菲尔
我有一个名为list.html.erb的页面的控制器如何在rails中动态添加内容?
当用户点击一个链接我想动态地将内容追加到页面并在之后执行JavaScript。 是否有可能有一个呈现js.erb文件的方法,并将包含内容的变量放入此文件中?
最好菲尔
与那里描述:http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to你需要使用
link_to 'Something', 'somewhere', remote: true
是的,当然。不过,这可能不是最佳的行动方案。
如果您通过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
}
});
您可以在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 ID列表页面的div标签添加的内容“部分”