简体   繁体   English

Javascript文件的相对URL

[英]Relative urls for Javascript files

I have some code in a javascript file that needs to send queries back to the server. 我在javascript文件中有一些代码需要将查询发送回服务器。 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. 问题是,我如何找到我所在脚本的URL,因此我可以为ajax构建一个正确的请求URL。

Ie, the same script is included on / , /help , /whatever , and so on, while it will always need to request from /data.json . 即,相同的脚本包含在//help/whatever等等,而它始终需要从/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. 我有办法解决我包含Javascript(ez-publish模板)的相对URL,但不在javascript文件本身内。

Are there small scripts that will work on all browsers made for this? 是否有适用于所有浏览器的小脚本?

For this I like to put <link> elements in the page's <head> , containing the URLs to use for requests. 为此,我喜欢将<link>元素放在页面的<head> ,其中包含用于请求的URL。 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/"/>

and can be retrieved by Javascript with: 并可以通过Javascript检索:

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

document.location.href将为您提供当前URL,然后您可以使用JavaScript的字符串函数进行操作。

There's no way that the client can determine the webapp root without being told by the server as it has no knowledge of the server's configuration. 客户端无法在没有被服务器告知的情况下确定webapp根目录,因为它不知道服务器的配置。 One option you can try is to use the base element inside the head element, getting the server to generate it dynamically rather than hardcoding it (so it shows the relevant URL for each server): 您可以尝试的一个选项是使用head元素内的基本元素,让服务器动态生成它而不是硬编码(因此它显示了每个服务器的相关URL):

<base href="http://path/to/webapp/root/" />

All URLs will then be treated as relative to this. 然后将所有URL视为相对于此。 You would therefore simply make your request to /data.json. 因此,您只需向/data.json发出请求即可。 You do however need to ensure that all other links in the application bear this in mind. 但是,您需要确保应用程序中的所有其他链接牢记这一点。

If the script knows its own filename, you can use document. 如果脚本知道自己的文件名,则可以使用文档。 getElementsByTagName (). getElementsByTagName ()。 Iterate through the list until you find the script that matches yours, and extract the full (or relative) url that way. 遍历列表,直到找到与您匹配的脚本,然后以这种方式提取完整(或相对)URL。

Here's an example: 这是一个例子:

function getScriptUrl ( name ) {
    var scripts = document.getElementsByTagName('script');
    var re = RegExp("(\/|^)" + name + "$");
    var src;
    for( var i = 0; i < scripts.length; i++){
        src = scripts[i].getAttribute('src');
        if( src.match(re) )
            return src;
    }
    return null;
}

console.log( 'found ' + getScriptUrl('demo.js') );

Take into consideration that this approach is subject to filename collisions. 考虑到这种方法受文件名冲突的影响。

I include the following code in my libraries main entry point (main.php): 我在我的库主入口点(main.php)中包含以下代码:

/**
 * Build current url, depending on protocal (http/https),
 * port, server name and path suffix
 */
$site_root = 'http';
if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") 
    $site_root .= "s";
$site_root .= "://" . $_SERVER["SERVER_NAME"];
if ($_SERVER["SERVER_PORT"] != "80")
    $site_root .= ":" . $_SERVER["SERVER_PORT"];
$site_root .= $g_config["paths"]["site_suffix"];

$g_config["paths"]["site_root"] = $site_root;

$g_config is a global array containing configuration options. $ g_config是包含配置选项的全局数组。 So site_suffix might look like: "/sites_working/thesite/public_html" on your development box, and just "/" on a server with a virtual host (domain name). 因此,site_suffix可能看起来像:开发框中的“/ sites_working / thesite / public_html”,以及具有虚拟主机(域名)的服务器上的“/”。

This method is also good, because if somebody types in the IP address of your development box, it will use that same IP address to build the path to the javascript folder instead of something like "localhost," and if you use "localhost" it will use "localhost" to build the URL. 这种方法也很好,因为如果有人输入你的开发盒的IP地址,它将使用相同的IP地址来构建javascript文件夹的路径而不是像“localhost”这样的东西,如果你使用“localhost”它将使用“localhost”来构建URL。

And because it also detects SSL, you wont have to worry about weather your resources will be sent over HTTP or HTTPS if you ever add SSL support to your server. 并且因为它还检测SSL,所以如果您曾向服务器添加SSL支持,则不必担心通过HTTP或HTTPS发送资源的天气。

Then, in your template, either use 然后,在您的模板中,使用

<link id="site_root" href="<?php echo $g_config["paths"]["site_root"] ?>"/>

Or 要么

<script type = "text/javascript">
var SiteRoot = "<?php echo $g_config["paths"]["site_root"]; ?>";
</script>

I suppose the latter would be faster. 我想后者会更快。

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

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