Rails (5.2.2) AJAX 要求部分不工作

Rails (5.2.2) AJAX call for partial not working

简短而贴心,我完全按照 this guide 进行了新的 rails 部署 (5.2.2),使用 rails g scaffold thing 来生成应用程序。

但是,在指南中 Targeted Changes 段落下进行部分 _show.html.erb 后,单击 "Change below" link_to 不呈现测试时的部分。我没有收到任何错误消息,并且 Rails 告诉我一切都呈现正常,但是当我单击 link.

时网站上没有任何反应

我错过了什么?


代码:

controllers/things_controller

class ThingsController < ApplicationController

  def index
    @things = Thing.all
  end

  def show
  end

end

config/routes.rb

Rails.application.routes.draw do
  root 'things#index'
  resources :things
end

things/index.html.erb

<%# /app/views/things/index.html.erb %>
<%= link_to 'Change Below', thing_path(42), remote: true %>

<div id="target-for-change">
  Now you see "ME"!
</div>

things/show.js.erb

<%# /app/views/things/show.js.erb %>
$("#target-for-change").html("<%= j render(partial: 'show') %>");

things/_show.html.erb

<%# /app/views/things/_show.html.erb %>
Now you don't!

浏览器控制台输出:

Uncaught ReferenceError: $ is not defined
    at <anonymous>:1:1
    at processResponse (rails-ujs.self-d109d8c5c0194c8ad60b8838b2661c5596b5c955987f7cd4045eb2fb90ca5343.js?body=1:268)
    at rails-ujs.self-d109d8c5c0194c8ad60b8838b2661c5596b5c955987f7cd4045eb2fb90ca5343.js?body=1:196
    at XMLHttpRequest.xhr.onreadystatechange (rails-ujs.self-d109d8c5c0194c8ad60b8838b2661c5596b5c955987f7cd4045eb2fb90ca5343.js?body=1:251)

您需要在项目中添加 jquery。将此行添加到 application.html.erb

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

或者您可以使用 gem jquery-rails

如您在控制台输出中所见,“$”未定义。 '$' 是 jQuery 的通用别名,所以当您这样做时:

$("#target-for-change").html("<%= j render(partial: 'show') %>");

您是在告诉 jQuery 查找某个标识符。问题是您没有在项目中包含该库。一种方法是在您的 gemfile 中添加这一行:

gem 'jquery-rails'

然后在你的 assets/javascripts/application.js

//= require jquery3