编辑:无论出于什么原因,我的资产都没有加载。我的javascript在服务器上返回404错误。
ORIGINAL:我知道在我的localhost上运行应用程序时jQuery会加载,因为; 1.我的应用程序工作,以及2.以下代码还告诉我在页面加载时加载jQuery。
if (typeof jQuery != 'undefined') {
// jQuery is loaded => print the version
alert(jQuery.fn.jquery);
}
问题是我将它推送到Heroku后,jQuery无效。上面的代码不再运行了,当我尝试运行$.post( "/time_records", {current_time: current_time});
时,我收到以下错误; ReferenceError: $ is not defined
当我在Heroku上运行我的Bundler时,它说Using jquery-rails (3.1.0)
的application.js
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .
的Gemfile
source 'https://rubygems.org'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.0.2'
# Use postgresql as the database for Active Record
gem 'pg'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 4.0.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .js.coffee assets and views
gem 'coffee-rails', '~> 4.0.0'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 1.2'
group :doc do
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', require: false
end
# Use ActiveModel has_secure_password
# gem 'bcrypt-ruby', '~> 3.1.2'
# Use unicorn as the app server
# gem 'unicorn'
# Use Capistrano for deployment
# gem 'capistrano', group: :development
# Use debugger
# gem 'debugger', group: [:development, :test]
答案 0 :(得分:5)
由于您将应用程序放在Heroku上,请检查Javascript文件是否未在线返回 404 HTTP错误。如果是这样,jQuery永远不会被加载...
这可能是由于您的配置中存在多个错误(来自本地配置的绝对文件路径或其他)
答案 1 :(得分:3)
(感谢@Maxime指出我正确的方向。)
根据 Heroku Rails支持页面,作为编译阶段的最后一项任务,执行assets:precompile
Rake任务。如果您定义了assets:precompile
Rake任务,并且没有public/assets/manifest-*.json
文件。这将编译所有资产并将它们放在您的公共目录中。 如果此资产编译失败,部署也将失败。
我的部署没有失败,所以我认为这一步发生得很顺利,但当我查看日志时说它
-----> Preparing app for Rails asset pipeline
Running: rake assets:precompile
Asset precompilation completed (2.49s)
Cleaning assets
Running: rake assets:clean
-----> WARNINGS:
Include 'rails_12factor' gem to enable all platform features
事实证明,如果不包含rails_12factor gem
页面,则无法正确找到资产,并返回404错误。修复很简单,将以下内容添加到您的GemFile中;
group :production do
gem 'rails_12factor'
end