javascript系列之通过js获取网站的根目录的两种方法

/**
 * 说明:
 * 1、host 主机名和当前url的端口号 返回:localhost:8080 
 * 2、hostname 主机名 返回:localhost 
 * 3、href 完整的url 返回:http://localhost:8080/huyao_soccer/huyao/tag/myplugin.jsp
 * 4、pathname 返回当前url的路径部分 返回:/huyao_soccer/huyao/tag/myplugin.jsp 
 * 5.protocol 协议 返回: http: 
 * 6.port 端口号 返回:8080 
 */


/**
 * 第一种获取获取网站的根目录
 * @returns
 */
function getRoot(){
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;   
}
/**
 * 第二种获取获取网站的根目录
 * @returns
 */
function getBasePath(){ 
var obj=window.location; 
var contextPath=obj.pathname.split("/")[1]; 
var basePath=obj.protocol+"//"+obj.host+"/"+contextPath; 
return basePath; 
} 

你可能感兴趣的:(javascript)