有时我们做一些后台访问时,需要直接在js里面获取项目的根路径来拼接后中对应的action;
如上:
第一步:
此时就需要获得对应的一串url;
获取方法:
例如:
http://www.baidu.com/baidu/index.html
在js里面怎样才能获取“
http://www.baidu.com”呢?
//获取当前的网址的全文
var currentUrl =
window.document.location.href;
第二步:
//获取端口号之后的项目路径的信息(如:baidu/baidu1/baidu2)
var projectName = window.document.location.pathname;
第三步:
//获取当前网址到项目名称片的位置
注:通过js的indexOf方法截取网址全文
pathname之前的长度;
var pos = currentUrl.indexOf(pathname);
第四步:
//获取最终的值:"
http://www.baidu.com"
var localhostPath = currentUrl.substring(0,pos);
第五步:
这一步骤如果是在本地的话,可以使用;如果是外网环境的话,则不需要使用。
注:如上的话,此值就是“baidu”;
var projectNameReal = projectName.substring(0,projectName.substr(1).indexOf("/")+1);
至此获取项目根路径结束,若在项目中使用,可将以上代码封装为公共函数,供项目使用。