Rails AJAX - 获取下拉选择以填充表格 [英] Rails AJAX - getting a dropdown selection to populate a table
问题描述
我正在尝试从下拉列表中选择一个选项来填充同一页面中的表格,使用 AJAX 以便在不刷新页面的情况下显示更改.我已经为远程调用制定了代码,并将自定义操作添加到控制器,但我不知道如何将返回的信息放入我得到的表中.目前,该表只是遍历所有项目,但我希望它只显示所选项目的信息.
I'm trying to get a selection from a dropdown to populate a table in the same page, using AJAX so that changes appear without a page refresh. I've got as far as working out the code for the remote call, and adding the custom action to the controller, but I don't know how to get the returned information into the table I've got. At the moment, the table is just looping through all the projects, but I want it to only display the info for the one project that is selected.
我需要在 JS (rjs?) 文件中写入什么才能让它处理返回的信息,以及我需要对现有表进行哪些更改以确保它显示正确的信息?
What would I need to write in a JS (rjs?) file to get it to process the returned information, and what changes would I need to make to the existing table to make sure that it is displaying the correct info?
下拉(使用 AJAX 调用):
Dropdown (with AJAX call):
<%= collection_select :id, Project.all, :id, :name, :onchange => remote_function(:url=>{:action => 'populate_projects'}) %>
控制器动作:
def populate_projects
@project = Project.find(params[:id])
end
和现有表:
<table>
<tr>
<th>Name</th>
<th>Category</th>
<th>Budget</th>
<th>Deadline</th>
<th>Company ID</th>
<th></th>
<th></th>
<th></th>
</tr>
<% @projects.each do |project| %>
<tr>
<td><%= project.name %></td>
<td><%= project.category %></td>
<td><%= number_to_currency(project.budget, :unit => "£") %></td>
<td><%= project.deadline.strftime("%A, %d %B %Y") %></td>
<td><%= project.company_id %></td>
<td><%= link_to 'More', project %></td>
<td><%= link_to 'Edit', edit_project_path(project) %></td>
<td><%= link_to 'Delete', project, confirm: 'Are you sure?', method: :delete %></td>
</tr>
<% end %>
</table>
推荐答案
假设你正在使用 jquery
Assume you're using jquery
<%= collection_select :project, :id, Project.all, :id, :name, {}, {:onchange => '$.get("/populate_projects")'} %>
然后在您的控制器中
def populate_projects
@project = Project.find(params[:id])
respond_to do |format|
...
format.js { render 'populate_projects', :formats => [:js] }
...
end
end
最后,创建 populate_projects.js.erb
并编写任何更改表内容脚本.@project
在该脚本中可用.
finally, create populate_projects.js.erb
and write any change table content script. @project
is available in that script.
这篇关于Rails AJAX - 获取下拉选择以填充表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!