Staale Staale - 1 year ago 91
Javascript Question

Relative urls for Javascript files

I have some code in a javascript file that needs to send queries back to the server. The question is, how do I find the url for the script that I am in, so I can build a proper request url for ajax.

I.e., the same script is included on

, and so on, while it will always need to request from
. Additionally, the same site is run on different servers, where the
-folder might be placed differently. I have means to resolve the relative url where I include the Javascript (ez-publish template), but not within the javascript file itself.

Are there small scripts that will work on all browsers made for this?

Answer Source

For this I like to put <link> elements in the page's <head>, containing the URLs to use for requests. They can be generated by your server-side language so they always point to the right view:

<link id="link-action-1" href="${reverse_url ('action_1')}"/>


<link id="link-action-1" href="/my/web/root/action-1/"/>

and can be retrieved by Javascript with:

document.getElementById ('link-action-1').href;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download