本文介绍如何使用JavaScript获取Web应用的根目录路径。通过解析window.document.location.href和pathname,利用indexOf和substring方法提取域名及项目路径部分,从而得到完整的根目录地址。
JavaScript获取Web应用根目录路径的方法
实现代码如下:
<script>
function getRootPath(){
var strFullPath=window.document.location.href;
var strPath=window.document.location.pathname;
var pos=strFullPath.indexOf(strPath);
var prePath=strFullPath.substring(0,pos);
var postPath=strPath.substring(0,strPath.substr(1).indexOf('/')+1);
return(prePath+postPath);
}
var webpath=getRootPath(); //webpath就是目录路径变量
</script>