在Javascript中获取网站根

Getting the website root in Javascript

本文关键字:网站 获取 Javascript      更新时间:2023-09-26

说我正在开发一个网站。我需要得到根(网站)动态(开发和生产)。有没有办法在JS中做到这一点?

我在服务器上使用asp.net mvc 3

是:window.location.hostname

参见:如何在JavaScript中提取URL的主机名部分

引用链接:

您可以连接位置协议和主机:Var root = location。Protocol + '//' + location.host;对于url,例如'https://stackoverflow.com/questions',它将返回'http://stackoverflow.com'

我创建了一个函数来获取实数根:

function root() {
        var scripts = document.getElementsByTagName( 'script' ),
            script = scripts[scripts.length - 1],
            path = script.getAttribute( 'src' ).split( '/' ),
            pathname = location.pathname.split( '/' ),
            notSame = false,
            same = 0;
        for ( var i in path ) {
            if ( !notSame ) {
                if ( path[i] == pathname[i] ) {
                    same++;
                } else {
                    notSame = true;
                }
            }
        }
        return location.origin + pathname.slice( 0, same ).join( '/' );
    }

在加载js文件时调用此函数一次。
要使它工作,你必须将它作为js-file包含。

<标题>用法:
var basepath = root();

下面是一些例子:

location.host: 'http://test.com'
location.path: '/myapp/controller/action/id'

这将导致:

http://test.com/myapp