使用ajax请求

时间:2017-05-12 15:38:38

标签: javascript jquery ruby-on-rails ruby ajax

我是铁杆新手,我正在尝试为学校做一个简单的项目。

我已经按照以下方式生成了一个脚手架。

rails generate scaffold Book title:string content:text code:string

我正在尝试做的是,当我点击链接时,在同一页面上显示div的列表ID(localhost:3000 / books)。我尝试按照this程序进行操作,但似乎没有用,当我点击/ 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>

my books_controller的索引方法

def index
    @books = Book.all

    respond_to do |format|
      format.html
      format.js
    end
  end

_books partial

<% @books.each do |book| %>
    <div class="book">
      <%= book.id %>
    </div>
<% end %>

和books / index.js.erb

$("#content").html("<%= j (render 'books') %>");

当我点击应该呈现部分的链接时,我在终端中得到了这个,并且页面上没有显示任何内容。

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)

我想我错过了一些东西,但我真的无法弄明白为什么。有任何想法吗?谢谢

PS:Rails版本:5.1.0和ruby 2.4.0

2 个答案:

答案 0 :(得分:1)

Rails 5.1并不依赖于jQuery。这段代码:

$('#content').html("<%= j (render 'books') %>");

是jQuery代码。如果您添加jquery-rails gem并按照文档说明,那么您的代码应该可以正常运行。

答案 1 :(得分:0)

我不确定你的代码问题出在哪里,但我可以建议一个更优雅的选择。我建议将一个jquery onClick处理程序绑定到你的链接并让它对服务器执行一个ajax请求 - 要么是另一个视图,要么重新编码同一个视图 - 它发回一个包含你所有数据的json对象,ajax成功处理程序可以然后操纵页面中的html。像这样:

$("#all_books_link").click(function() {
  $.ajax({
     dataType: "json",
     url: <PUT ALL BOOKS SERVER URL HERE>,
     success:function(data) {
        for (var key in data) {
           $("#content").append("<div>"+data[key]+"</div>"
        }
     }
   });
});

你的服务器端rails函数应该返回一个json对象,而不是实际的HTML。