Ruby-on-rails 如何将 Javascript 文件加载到 rails html erb

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18533969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:37:59  来源:igfitidea点击:

how to load a Javascript file to rails html erb

ruby-on-rails

提问by co2f2e

Um trying to load a javascript file as follows to my html.erb file

嗯,我试图将一个 javascript 文件如下加载到我的 html.erb 文件中

 <script src="/public/javascripts/test.js" type="text/javascript" /> 

its available on the public folder and its in the root directory

它在公共文件夹和根目录中可用

root/public/javascript

根/公共/javascript

but it giving me an error saying

但它给了我一个错误说

 "NetworkError: 404 Not Found  - http://0.0.0.0:3000/public/javascripts/test.js"

what could possibly wrong ? is there a different way to include a javascipt file in rails ?

可能有什么问题?有没有其他方法可以在 rails 中包含 javascipt 文件?

回答by Jarred Humphrey

If the javascript file is in any of the asset folders (assets, vendor, bundle) for Rails 3.x) you can add the script to your html.erb file by adding the following:

如果 javascript 文件位于 Rails 3.x 的任何资产文件夹(assets、vendor、bundle)中),您可以通过添加以下内容将脚本添加到 html.erb 文件中:

<%= javascript_include_tag('test.js') %>

回答by j_mcnally

You don't use public. Public is the implied root of the server.

你不使用公共。Public 是服务器的隐含根。

The server will look for a file in public, then try to route it through your router if it doesn't find a match.

服务器将公开查找文件,如果找不到匹配项,则尝试通过您的路由器路由它。

You also may want to consider using the javascript_include_taghelper if you are using the asset pipeline.

javascript_include_tag如果您正在使用资产管道,您可能还需要考虑使用帮助程序。

回答by TheIrishGuy

Rails defaults to using the asset pipeline, so custom js files need to go into the app/assets/javascript directory. Than you wouldn't even need to load the file in your view.

Rails 默认使用资产管道,因此自定义 js 文件需要进入 app/assets/javascript 目录。比您甚至不需要在您的视图中加载文件。

but as to your question.

但至于你的问题。

To serve the files from the public directory, you will need to enable a config setting

要从公共目录提供文件,您需要启用配置设置

config.serve_static_assets = true

You'd commonly put this in one of you environment config files.

您通常会将其放在其中一个环境配置文件中。

回答by techvineet

To server files from public directory do above setting and hit

从公共目录服务器文件做上面的设置并点击

config.serve_static_assets = true
<script src="/javascripts/test.js" type="text/javascript" />