ruby-on-rails - 使用 AJAX 单击 link_to 后如何在同一页面上呈现部分

标签 ruby-on-rails ajax asynchronous partial

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

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

我的客户列表代码:

<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" %>

我展示客户的部分:
<p>
  <strong>Name:</strong>
  <%= @customer.name %>
  <%= @customer.id %>
</p>

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

你能帮我一些想法吗?

最佳答案

您基本上希望使用 AJAX 来显示客户的详细信息。为此,您可以使用 remote: true rails 为 link_to 提供的选项 helper 。我们接下来要做的事情:

  • 创建一个包含加载数据的 div。在这种情况下 div#current_customer
  • 添加 remote: true到您的链接:
    <td><%= link_to 'Show', customer, remote: true %></td>
    
  • 命名您的部分 customers/_show.html.erb (不要忘记 _ 所以它可以被称为部分):
    <p>
       <strong>Name:</strong>
       <%= @customer.name %>
       <%= @customer.id %>
    </p>
    
    <%= link_to 'Edit Customer', edit_customer_path(@customer) %> |
    <%= link_to 'Back', customers_path %> # You should remove this link
    
  • show 中响应 Javascript CustomersController 中的方法:
    respond_to do |format|
      format.js {render layout: false} # Add this line to you respond_to block
    end
    
  • 创建您的 show.js.erb View ,它将在 respond_to :js 时处理前端更改将被调用(在这种情况下由 remote: true 触发)
  • 告诉 show.js.erb它必须做什么(用你的部分替换 #current_customer 内容,使用正确的 @customer ):

  • 客户/show.js.erb
    $("#current_customer").html("<%= escape_javascript(render partial: 'customers/show', locals: { customer: @customer } ) %>");
    
    客户/index.html.erb




    姓名
    行动


















    <div id="current_customer"> # This will will contain the partial 
    </div>
    

    关于ruby-on-rails - 使用 AJAX 单击 link_to 后如何在同一页面上呈现部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35899433/

    相关文章:

    ruby-on-rails - 通过回形针上传大文本文件的性能问题

    ruby-on-rails - 使用 Rails 验证两个属性中仅存在一个的最优雅方法是什么?

    javascript - 为什么 iframe 这么慢?

    php - 需要添加功能

    javascript - 多个链接的 getElementsByClassName 问题

    c# - 在 .Net 中寻找 'Asynchronous' 字的解释?

    mysql - 数据库中删除了尖括号 (<>) 之间的字符?

    ruby-on-rails - 如何创建没有密码的用户并稍后使用 Devise 表单进行设置?

    c# - HttpWebRequest 分块/异步 POST

    javascript - 如果用户中止连接到服务器(连接时刷新、关闭浏览器等),如何停止执行所有功能(多个异步等)