使用ajax请求在同一页面中显示部分 [英] Show partial in the same page using ajax request
问题描述
我是Rails的新手,我正在尝试为学校做一个简单的项目.
I'm new to rails and i'm trying to do a simple project for school.
我已经开始制作了如下的脚手架.
I have generated a scaffold as follows to begin.
rails generate scaffold Book title:string content:text code:string
我想做的是,当我单击链接时,在同一页面上的div中显示一个图书ID的列表(localhost:3000/books).我尝试遵循此过程,但似乎没有要正常工作,当我单击/books页面末尾的链接
What I'm trying to do, is to display a list of the books id's in a div on the same page (localhost:3000/books) when I click on a link. I tried to follow this procedure but it doesn't seem to work, nothing is visibly rendered on the page when I click the link at the end of the /books page
这是我的books/index.html.erb
Here is my books/index.html.erb
<p id="notice"><%= notice %></p>
<h1>Books</h1>
<table>
<thead>
<tr>
<th>Title</th>
<th>Content</th>
<th>Code</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% @books.each do |book| %>
<tr>
<td><%= book.title %></td>
<td><%= book.content %></td>
<td><%= book.code %></td>
<td><%= link_to 'Show', book %></td>
<td><%= link_to 'Edit', edit_book_path(book) %></td>
<td><%= link_to 'Destroy', book, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
</tbody>
</table>
<br>
<%= link_to 'New Book', new_book_path %>
<br>
<%= link_to 'All books', books_path, remote: true %>
<br>
<br>
<div id="content" >
</div>
我的books_controller的索引方法
my books_controller's index method
def index
@books = Book.all
respond_to do |format|
format.html
format.js
end
end
部分_books
<% @books.each do |book| %>
<div class="book">
<%= book.id %>
</div>
<% end %>
和books/index.js.erb
and the books/index.js.erb
$("#content").html("<%= j (render 'books') %>");
当我单击应该呈现部分内容的链接时,我在终端中得到了此内容,页面上没有任何显示.
When I click on the link that should render the partial, I get this in the terminal and nothing is displayed on the page.
Started GET "/books" for 127.0.0.1 at 2017-05-12 17:35:02 +0200
Processing by BooksController#index as JS
Rendering books/index.js.erb
Book Load (0.3ms) SELECT "books".* FROM "books"
Rendered books/_books.html.erb (2.4ms) [cache miss]
Rendered books/index.js.erb (3.9ms)
Completed 200 OK in 8ms (Views: 6.0ms | ActiveRecord: 0.3ms)
我想我缺少了一些东西,但是我真的不知道为什么.有任何想法吗?谢谢
I imagine I am missing something, but I really can't figure out why. Any ideas? thank you
PS:Rails版本:5.1.0和ruby 2.4.0
PS: Rails version: 5.1.0 and ruby 2.4.0
推荐答案
Rails 5.1对jQuery没有依赖性.这段代码:
Rails 5.1 doesn't have a dependency on jQuery. This code:
$('#content').html("<%= j (render 'books') %>");
是jQuery代码.如果您添加jquery-rails
gem并遵循文档,则您的代码应该可以使用.
is jQuery code. If you add the jquery-rails
gem and follow the documentation, your code should work.
这篇关于使用ajax请求在同一页面中显示部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!