Ruby on rails 如何使用AJAX在单击链接后在同一页面上呈现部分内容

Ruby on rails 如何使用AJAX在单击链接后在同一页面上呈现部分内容,ruby-on-rails,ajax,asynchronous,partial,Ruby On Rails,Ajax,Asynchronous,Partial,我有一份顾客名单。每个客户都有一个链接,链接到客户页面并显示其数据 我想链接到客户表下同一页上呈现的部分内容。在使用表初始化“页面”时,应该加载一个类似“选择客户”的空白页面 客户列表的我的代码: <h1>Listing Customers</h1> <table> <thead> <tr> <th>Name</th> <th colspan="3">Action

我有一份顾客名单。每个客户都有一个链接,链接到客户页面并显示其数据

我想链接到客户表下同一页上呈现的部分内容。在使用表初始化“页面”时,应该加载一个类似“选择客户”的空白页面

客户列表的我的代码:

<h1>Listing Customers</h1>

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th colspan="3">Actions</th>
    </tr>
  </thead>

  <tbody>
    <% @customers.each do |customer| %>
      <tr>
        <td><%= customer.name %></td>
        <td><%= link_to 'Show', customer %></td>
        <td><%= link_to 'Edit', edit_customer_path(customer) %></td>
        <td><%= link_to 'Destroy', customer, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>

  </tbody>
</table>

<br>

<%= link_to 'New Customer', new_customer_path, class: "button", id: "new_customer" %>
列出客户
名称
行动

<div id="current_customer"> # This will will contain the partial 
</div>
用于显示客户的我的部分:

<p>
  <strong>Name:</strong>
  <%= @customer.name %>
  <%= @customer.id %>
</p>

<%= link_to 'Edit Customer', edit_customer_path(@customer) %> |
<%= link_to 'Back', customers_path %>

名称:

|

你能帮我一些想法吗?

你基本上想使用AJAX来显示客户的详细信息。为此,您可以使用rails提供的
link\u to
helper的
remote:true
选项。我们下一步要做什么:

  • 创建一个将包含加载数据的div。在这种情况下,
    div#当前客户

  • remote:true
    添加到您的链接:

    <td><%= link_to 'Show', customer, remote: true %></td>
    
  • CustomersController
    中的
    show
    方法中响应Javascript:

    respond_to do |format|
      format.js {render layout: false} # Add this line to you respond_to block
    end
    
  • 创建
    show.js.erb
    视图,该视图将在调用
    respond\u to:js
    时处理前端更改(在这种情况下由
    remote:true
    触发)

  • 告诉show.js.erb它必须做什么(使用正确的
    @customer
    #当前客户
    内容替换为您的部分内容):

  • 客户/show.js.erb
    $(“当前客户”).html(“”);
    
    customers/index.html.erb 名称 行动
    <div id="current_customer"> # This will will contain the partial 
    </div>
    
    #这将包含部分
    
    <div id="current_customer"> # This will will contain the partial 
    </div>