简体   繁体   English

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

[英]how to load a Javascript file to rails html erb

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文件?

如果javascript文件位于Rails 3.x的任何资产文件夹(资产,供应商,软件包)中,则可以通过添加以下内容将脚本添加到html.erb文件中:

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

Rails defaults to using the asset pipeline, so custom js files need to go into the app/assets/javascript directory. Rails默认使用资产管道,因此自定义js文件需要进入app / assets / javascript目录。 Than you wouldn't even need to load the file in your view. 甚至不需要在视图中加载文件。

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. 你通常把它放在你的一个环境配置文件中。

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_tag helper if you are using the asset pipeline. 如果您正在使用资产管道,您还可以考虑使用javascript_include_tag帮助程序。

To server files from public directory do above setting and hit 从公共目录服务器文件执行上面的设置并点击

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM