rails使用ajax渲染部分(在加载时 - 请求后不是)

时间:2022-10-08 16:42:03

I must be overlooking something here. Any help would be appreciated.

我必须在这里忽视一些事情。任何帮助,将不胜感激。

I want to load a partial on a page with ajax when I visit a page. ONLY on visit, not after a request is being made. So in other words, I visit the page, all HTML displays instantly, and then a section of the page loads the data with ajax into the partial and it's displayed.

我想在访问页面时在带有ajax的页面上加载部分内容。仅在访问时,而不是在提出请求后。换句话说,我访问页面,立即显示所有HTML,然后页面的一部分将带有ajax的数据加载到partial中并显示。

When I load my index view it loads the page, but it doesn't load the partial. I get this error in console:

当我加载索引视图时,它会加载页面,但它不会加载部分。我在控制台中收到此错误:

Unexpected identifier 'sites'. Expected ')' to end a argument list

index.html.erb - for Site.rb

index.html.erb - 用于Site.rb

<h1>Listing sites</h1>

<div id="sites-container">

</div>

<%= link_to 'New Site', new_site_path %>

_online_status.html.erb - partial

_online_status.html.erb - 部分

<table>
  <thead>
    <tr>
      <th>Location</th>
      <th>IP Address</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @sites.each do |site| %>
      <tr>
        <td><%= site.name %></td>
        <td><%= site.ip %> <%= online_status(site.ip) %></td>
        <td><%= link_to 'Show', site %></td>
        <td><%= link_to 'Edit', edit_site_path(site) %></td>
        <td><%= link_to 'Destroy', site, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  </tbody>
</table>

sites_helper.html.erb

def online_status(ip)
  ping_count = 2
  result = `ping -q -c #{ping_count} #{ip_address}`

  if $?.exitstatus == 0
    return "Online"
  else
    return "Unreachable"
  end
end

application.js

$(document).ready(function() {
  $("#sites-container").replaceWith('<%= escape_javascript(render 'sites/online_status') %>');
});

1 个解决方案

#1


0  

$(document).ready(function() {
  $("#sites-container").replaceWith('<%= j render "sites/online_status" %>');
});

#1


0  

$(document).ready(function() {
  $("#sites-container").replaceWith('<%= j render "sites/online_status" %>');
});