javascript获取项目根目录

概述

在项目开发中,大部分项目访问,都会有项目名称;在js中,怎么自动获取根目录地址?

  • 无项目名称(直接访问根目录)
  • 有项目名称(需要加上项目名称访问)

分析

  1. 新建一个check.txt空文件,放入项目中
  2. 获取根目录/项目名称(url中的第一个路径),先通过ajax同步过/请求此文件,如果请求成功,说明此路径匹配,请求失败,再通过项目名称请求第二次。
  3. 请求成功后,把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;
}

//type类型,1:根路径,2:项目目录
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");
}