js中获取上下文路径的方法

来源:互联网 发布:java五子棋人机对战 编辑:程序博客网 时间:2024/05/16 10:41
var path=null;
//js获取项目访问的url地址的方法
//这样写就不用每个jsp页面都写个隐藏域传递path这个参数了,页面多的时候比较麻烦
function getRootPath(){
     //获取当前网址,如:http://localhost:8080/supermarket/user.do?method=query
    var currentWwwPath=window.document.location.href;  
    //获取主机地址之后的目录,如:/supermarket/user.do(注意:不包括?后面传递的参数)
    var pathName=window.document.location.pathname;  
 
    //获取/uimcardprj中/的位置(也就是主机地址后面的/),这里是:21
    var position=currentWwwPath.indexOf(pathName);  
  
    //获取主机地址,如:http://localhost:8080
    var localhostPath=currentWwwPath.substring(0,position);  


    //获取带"/"的项目名,如:/supermarket 
  //   /supermarket(0是为了把/也截取出来)
    var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);  
   //alert(pathName.substr(1).indexOf('/')); //这里是11,最后用substring截取字符串时,不包括第二个参数,所以要+1
    //pathName.substr(1)的结果是:supermarket/user.do
    //pathName.substr(1).indexOf('/')的结果是:supermarket的长度,就是11
    //indexOf('/')指的是字符串/首次出现的位置
  
    path=projectName;
    return path;
}

   path=getRootPath();

//这样就可以在js中拼接路径了


原创粉丝点击