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 badges
Add a ment  | 

3 Answers 3

Reset to default 7

There'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