【发布时间】:2019-11-13 03:24:21
【问题描述】:
我是 Ruby on Rails 的新手,我正在尝试让 ajax 与 Tutorialspoint 上的 ajax 教程一起工作。但即使在我将“jquery-rails”gem 包含到 gemfile 中并使用“bundle install”命令之后,我的浏览器控制台中仍然出现“未捕获的 ReferenceError:$ 未定义”错误,并且 ajax 函数不起作用。
我仍然需要刷新页面才能看到结果。
(我用脚手架生成代码)
我的 index.view.erb
<h1>Ponies</h1>
<table>
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% @ponies.each do |pony| %>
<tr>
<td><%= pony.name %></td>
<td><%= pony.description %></td>
<td><%= link_to 'Show', pony %></td>
<td><%= link_to 'Edit', edit_pony_path(pony) %></td>
<td><%= link_to 'Destroy', pony, method: :delete, data: { confirm: 'Are you sure?' }, :remote => true, :class => 'delete_pony' %></td>
</tr>
<% end %>
</tbody>
</table>
<br>
<%= link_to 'New Pony', new_pony_path %>
我的 destroy.js.erb
$('.delete_pony').bind('ajax:success', function() {
$(this).closest('tr').fadeOut();
});
我的小马控制器.rb
...
def destroy
@pony.destroy
respond_to do |format|
format.html { redirect_to ponies_url, notice: 'Pony was successfully destroyed.' }
format.json { head :no_content }
format.js { render :layout => false }
end
end
...
宝石文件
...
gem 'jquery-rails'
...
浏览器控制台
Uncaught ReferenceError: $ is not defined
at <anonymous>:1:1
at processResponse (rails-ujs.js:283)
at rails-ujs.js:196
at XMLHttpRequest.xhr.onreadystatechange (rails-ujs.js:264)
应用程序.js
// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.
require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
// Uncomment to copy all static images under ../images to the output folder and reference
// them with the image_pack_tag helper in views (e.g <%= image_pack_tag 'rails.png' %>)
// or the `imagePath` JavaScript helper below.
//
// const images = require.context('../images', true)
// const imagePath = (name) => images(name, true)
//= require jquery
//= require jquery_ujs
【问题讨论】:
-
$( document ).on('turbolinks:load', function() {这个函数里面要写js代码... -
我仍然得到相同的结果。我认为问题是美元符号'$'。不知何故,rails 不允许我使用 jquery
-
jQuery.fn.jquery在控制台中检查 jquery 版本... -
我收到
Uncaught ReferenceError: jQuery is not defined错误 -
我确实这样做了,试图使这项工作。
//= require jquery和//= require jquery_ujs
标签: jquery ruby-on-rails ruby ajax