概述
在项目开发中,大部分项目访问,都会有项目名称;在js中,怎么自动获取根目录地址?
- 无项目名称(直接访问根目录)
- 有项目名称(需要加上项目名称访问)
分析
- 新建一个
check.txt
空文件,放入项目中
- 获取根目录
/
和项目名称
(url中的第一个路径),先通过ajax
同步过/
请求此文件,如果请求成功,说明此路径匹配,请求失败,再通过项目名称
请求第二次。
- 请求成功后,把
path
存入缓存sessionStorage
,用于提高效率(不需要每次都请求)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
|
var rootPath = getRootPath("1");
alert(rootPath);
function getRootPath(type){
var fsRootPath = sessionStorage.getItem("fsRootPath"); if(fsRootPath){ return fsRootPath; }
var path = "/"; if(type==="1"){ path="/"; }else if(type==="2"){ var pathName = document.location.pathname; if(window.location.protocol =="file:"){ var index = pathName.substr(1).lastIndexOf("/"); path = pathName.substr(0,index+1)+"/"; }else{ var index = pathName.substr(1).indexOf("/"); path = pathName.substr(0,index+1)+"/"; } } $.ajax({ type : "get", url : path+"check.txt", async : false, dataType : "text", success : function(data){ sessionStorage.setItem("fsRootPath",path); },error:function(){ if(type==="1"){ getRootPath("2"); } } }); return sessionStorage.getItem("fsRootPath"); }
|