[英]Rails AJAX - getting a dropdown selection to populate a table
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. 我正在尝试从下拉列表中进行选择,以使用AJAX填充同一页面中的表,以便在不刷新页面的情况下显示更改。 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.
目前,该表只是在所有项目中循环,但是我希望它仅显示所选一个项目的信息。
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? 我需要在JS(rjs?)文件中编写什么文件才能处理返回的信息,我需要对现有表进行哪些更改以确保其显示正确的信息?
Dropdown (with AJAX call): 下拉菜单(使用AJAX调用):
<%= collection_select :id, Project.all, :id, :name, :onchange => remote_function(:url=>{:action => 'populate_projects'}) %>
Controller action: 控制器动作:
def populate_projects
@project = Project.find(params[:id])
end
And the existing table: 和现有表:
<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>
Assume you're using jquery 假设您正在使用jQuery
<%= collection_select :project, :id, Project.all, :id, :name, {}, {:onchange => '$.get("/populate_projects")'} %>
then in your controller 然后在您的控制器中
def populate_projects
@project = Project.find(params[:id])
respond_to do |format|
...
format.js { render 'populate_projects', :formats => [:js] }
...
end
end
finally, create populate_projects.js.erb
and write any change table content script. 最后,创建
populate_projects.js.erb
并编写任何更改表内容脚本。 @project
is available in that script. 该脚本中可以使用
@project
。
Create one partial _project.html.erb
and render this partial in index page. 创建一个部分
_project.html.erb
并在索引页面中呈现此部分。 <%= render @projects %>
On change of project just render partial with project object and update page using rjs. <%= render @projects %>
在更改项目时,仅使用项目对象渲染部分内容,并使用rjs更新页面。
In js(RJS) file you need to call partial HTML file and this file have tables That you shown here in your question. 在js(RJS)文件中,您需要调用部分HTML文件,并且该文件具有您在问题中此处显示的表。
I hope this helps you. 我希望这可以帮助你。
Thanks. 谢谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.