Javascript文件的相对URL [英] Relative urls for Javascript files

查看:92
本文介绍了Javascript文件的相对URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在JavaScript文件中有一些代码需要将查询发送回服务器。问题是,如何找到我所在的脚本的url,所以我可以为ajax构建合适的请求url。

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.

即,同样的脚本是包括在 / / help / whatever 以及等等,而它总是需要从 /data.json 请求。此外,同一站点在不同的服务器上运行,其中 / - 文件夹可能放置不同。我有办法解决我包含Javascript(ez-publish模板)的相对url,但不包含在javascript文件本身中。

I.e., the same script is included on /, /help, /whatever, and so on, while it will always need to request from /data.json. 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?

推荐答案

为此,我想将< link> code>< head> 中的code>元素,其中包含用于请求的URL。它们可以由服务器端语言生成,因此它们总是指向正确的视图:

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')}"/>

变为

becomes

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

,并且可以通过Javascript检索:

and can be retrieved by Javascript with:

document.getElementById ('link-action-1').href;

这篇关于Javascript文件的相对URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆