简体   繁体   中英

Rails AJAX remote: true with dynamic id

I implemented a basic AJAX Call in Rails, which is working fine with this:

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")%>');

The problem is I generate up to 31 a-tags like the above one on a single page with the following loop and the form will of course always show up at the first one, no matter which link I click:

end_date.downto(start_date).each do |date|
    [...]

To make the form show up at the clicked link I tried to generate the ids dynamically like so:

id="new_day_ajax_<%= date.strftime('%d') %>" <!-- i.e. new_day_ajax_07 -->

but now I don't know how to pass this dynamic id into the new.js.erb. How can I know the dynamic id inside of the javascript?

Thanks in advance!

You can pass GET parameter and get it from params object in .erb view

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>

eg:

<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")%>');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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