[英]Getting the website root in Javascript
say I'm developing a website.com. 说我正在开发一个website.com。 I need to get the root (website.com) dynamically (for dev and production).
我需要动态获取根目录(website.com)(用于开发和生产)。 Is there a way to do it in JS?
有没有办法在JS中做到这一点?
I am using asp.net mvc 3 on the server. 我在服务器上使用asp.net mvc 3。
See: How to extract the hostname portion of a URL in JavaScript 请参阅: 如何在JavaScript中提取URL的主机名部分
Quote from the link: 从链接引用:
You could concatenate the location protocol and the host: var root = location.protocol + '//' + location.host;
您可以将位置协议和主机连接起来:var root = location.protocol +'//'+ location.host; For a url, let say ' https://stackoverflow.com/questions ', it will return ' http://stackoverflow.com '
对于URL,说“ https://stackoverflow.com/questions ”,它将返回“ http://stackoverflow.com ”
I created a function to get real root: 我创建了一个函数以获取实根:
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( '/' );
}
call this function once when the js-file is loaded. 加载js文件后,请调用此函数一次。
to make it work, you MUST include it as js-file. 要使其工作,您必须将其作为js文件包含在内。
var basepath = root();
here are some examples: 这里有些例子:
location.host: 'http://test.com'
location.path: '/myapp/controller/action/id'
this will result in: 这将导致:
http://test.com/myapp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.