admin管理员组文章数量:1287190
How can I get my hands on the project's root_path
in my application.js file?
I need it for a js plugin (codemirror) that needs to load other JS files. It's all fine and dandy if I say "/javascripts/needed_file.js", but what if I deploy my project to "/custom".
The code needs to do its magic all over the project and I would like it to be UJS, so it needs to be in a static javascript file.
Any solutions/simple hacks?
How can I get my hands on the project's root_path
in my application.js file?
I need it for a js plugin (codemirror) that needs to load other JS files. It's all fine and dandy if I say "/javascripts/needed_file.js", but what if I deploy my project to "/custom".
The code needs to do its magic all over the project and I would like it to be UJS, so it needs to be in a static javascript file.
Any solutions/simple hacks?
Share Improve this question edited Nov 21, 2016 at 14:57 Arslan Ali 17.8k9 gold badges63 silver badges83 bronze badges asked Jan 24, 2011 at 21:40 alexcepoialexcepoi 7081 gold badge10 silver badges20 bronze badges3 Answers
Reset to default 7There's no beautiful solution. I'd try one of these approaches:
Inspect
window.location.pathname
. Determine from this whether running from root or from a prefix url.Add something like
<script type="text/javascript" charset="utf-8">var ROOT_PATH = '<%= Rails.root_path %>';</script>
somewhere to the top of your layout file.Use this quite hackish function (I suspect that it might break with some of the HTML5 script attributes):
function urlOfCurrentFile() { var scripts = document.getElementsByTagName("script"); return scripts[scripts.length - 1].src; }
I have this in my header file.
<script type="text/javascript">
var BASE_URL = '<%= root_url %>';
</script>
Well, the best way I find is to leverage the power of JS to do so, like:
window.location.origin # http://localhost:3000/
It's gonna give you the plete hostname, with http://
, and the port number. Like in case of running Rails server locally, it will give you: http://localhost:3000
window.location.hostname # localhost
It's just gonna give you the name of host, and nothing about port or HTTP. Incase of Rails server running locally, it will give you: localhost
.
本文标签: javascriptRails rootpath in applicationjsStack Overflow
版权声明:本文标题:javascript - Rails root_path in application.js - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741306179a2371381.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论