如何使用 javascript 获取应用程序路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3677338/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How-to get the Application path using javascript
提问by user137348
If I have my application hosted in a directory. The application path is the directory name.
如果我的应用程序托管在目录中。应用程序路径是目录名称。
For example
例如
http://192.168.1.2/AppName/some.html
http://192.168.1.2/AppName/some.html
How to get using javascript the application name like in my case /AppName.
如何在我的情况下使用 javascript 应用程序名称/AppName。
document.domainis returning the hostname and document.URLis returning the whole Url.
document.domain正在返回主机名并document.URL返回整个 Url。
EDIT
编辑
Thr app path could be more complex, like /one/two/thre/
Thr 应用程序路径可能更复杂,例如 /one/two/thre/
采纳答案by donohoe
This will give you a result but would have to be modified if you have more levels (see commented code).
这将为您提供结果,但如果您有更多级别,则必须进行修改(请参阅注释代码)。
var path = location.pathname.split('/');
if (path[path.length-1].indexOf('.html')>-1) {
path.length = path.length - 1;
}
var app = path[path.length-2]; // if you just want 'three'
// var app = path.join('/'); // if you want the whole thing like '/one/two/three'
console.log(app);
回答by electron
window.location.pathname.substr(0, window.location.pathname.lastIndexOf('/'))
回答by irishbuzz
This should do the trick
这应该可以解决问题
function getAppPath() {
var pathArray = location.pathname.split('/');
var appPath = "/";
for(var i=1; i<pathArray.length-1; i++) {
appPath += pathArray[i] + "/";
}
return appPath;
}
alert(getAppPath());
回答by ?ime Vidas
(function(p) {
var s = p.split("/").reverse();
s.splice(0, 1);
return s.reverse().join("/");
})(location.pathname)
This is an expression... just copy-paste it to the place where you need that string. Or put it in a variable, so that you can use it multiple times.
这是一个表达式...只需将其复制粘贴到您需要该字符串的位置即可。或者把它放在一个变量中,这样你就可以多次使用它。
回答by myset
alert("/"+location.pathname.split('/')[1]);
alert("/"+location.pathname.split('/')[1]);
If your path is something like /myApp/...
如果您的路径类似于 /myApp/...
or
或者
function applicationContextPath() {
if (location.pathname.split('/').length > 1)
return "/" + location.pathname.split('/')[1];
else
return "/";
}
alert(applicationContextPath);

