Rails AJAX 远程:使用动态 ID 为真
Rails AJAX remote: true with dynamic id
我在 Rails 中实现了一个基本的 AJAX 调用,它运行良好:
index.html.erb
<a href="/days/new" data-remote="true" id="new_day_ajax">Add This day</a>
new.js.erb
$('#new_day_ajax').hide().after('<%= j render("form")%>');
问题是我使用以下循环在单个页面上生成了多达 31 个类似上面的 a-tag,并且无论哪个 link我点击:
end_date.downto(start_date).each do |date|
[...]
为了让表单在点击时显示 link 我尝试像这样动态生成 ID:
id="new_day_ajax_<%= date.strftime('%d') %>" <!-- i.e. new_day_ajax_07 -->
但现在我不知道如何将这个动态 ID 传递给 new.js.erb。我如何知道 javascript 中的动态 ID?
提前致谢!
您可以传递 GET 参数并从 .erb
视图中的 params
对象获取它
index.html.erb
<a href="/days/new?date=<%= date.strftime('%Y-%m-%d') %>"
data-remote="true"
id="new_day_ajax_<%= date.strftime('%Y-%m-%d') %>">Add This day</a>
例如:
<a href="/days/new?date=2016-10-08"
data-remote="true"
id="new_day_ajax_2016-10-08">Add This day</a>
new.js.erb
$('#new_day_ajax_<%= params[:date] %>').hide().after('<%= j render("form")%>');
我在 Rails 中实现了一个基本的 AJAX 调用,它运行良好:
index.html.erb
<a href="/days/new" data-remote="true" id="new_day_ajax">Add This day</a>
new.js.erb
$('#new_day_ajax').hide().after('<%= j render("form")%>');
问题是我使用以下循环在单个页面上生成了多达 31 个类似上面的 a-tag,并且无论哪个 link我点击:
end_date.downto(start_date).each do |date|
[...]
为了让表单在点击时显示 link 我尝试像这样动态生成 ID:
id="new_day_ajax_<%= date.strftime('%d') %>" <!-- i.e. new_day_ajax_07 -->
但现在我不知道如何将这个动态 ID 传递给 new.js.erb。我如何知道 javascript 中的动态 ID?
提前致谢!
您可以传递 GET 参数并从 .erb
视图中的 params
对象获取它
index.html.erb
<a href="/days/new?date=<%= date.strftime('%Y-%m-%d') %>"
data-remote="true"
id="new_day_ajax_<%= date.strftime('%Y-%m-%d') %>">Add This day</a>
例如:
<a href="/days/new?date=2016-10-08"
data-remote="true"
id="new_day_ajax_2016-10-08">Add This day</a>
new.js.erb
$('#new_day_ajax_<%= params[:date] %>').hide().after('<%= j render("form")%>');