首页 > 代码库 > JavaScript获取当前url根目录(路径)

JavaScript获取当前url根目录(路径)

jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<%
  String path = request.getContextPath();
  String basePath = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort()+ path + "/";

%>
<!DOCTYPE html>
<html>
<head>

<base href="http://www.mamicode.com/">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="http://www.mamicode.com/<%=basePath%>/css/mycss/login_css.css" rel="stylesheet" type="text/css" />

 

</head>

 

js:

方法一

function getRealPath(){

  //获取当前网址,如: http://localhost:8083/myproj/view/my.jsp

  var curWwwPath=window.document.location.href;

  //获取主机地址之后的目录,如: myproj/view/my.jsp

  var pathName=window.document.location.pathname;

  var pos=curWwwPath.indexOf(pathName);

  //获取主机地址,如: http://localhost:8083

  var localhostPaht=curWwwPath.substring(0,pos);

  //获取带"/"的项目名,如:/myproj

  var projectName=pathName.substring(0,pathName.substr(1).indexOf(‘/‘)+1);

  //得到了 http://localhost:8083/myproj

  var realPath=localhostPaht+projectName;

  alert(realPath);

}

方法二:

function getRootPath_dc() {
  var pathName = window.location.pathname.substring(1);
  var webName = pathName == ‘‘ ? ‘‘ : pathName.substring(0, pathName.indexOf(‘/‘));
  if (webName == "") {
    return window.location.protocol + ‘//‘ + window.location.host;
  }
  else {
    return window.location.protocol + ‘//‘ + window.location.host + ‘/‘ + webName;
  }
}

 

常识补充:

 

  1. //获取当前窗口的Url    
  2. //returnUrl=http://localhost:8080/shopping/buyCart.shtml?skuId=510&amount=1  
  3.     window.location.href      
  4. //获取当前窗口的主机名 例如:http://localhost:8080       
  5.     window.location.host              
  6. //获取当前窗口的端口  例如: 8080  
  7. window.location.port  
  8. //获取当前窗口的路径 例如: /shopping/buyCart.shtml  
  9.     window.location.pathname  
  10. //获取当前文档的Url  
  11.     document.URL  
  12. //获取参数  例如: ?skuId=510&amount=1  
  13. window.location.search  
  14. //跳出当前窗口,打开新窗口  
  15. window.open(url);  
  16. document默示的是一个文档对象,window默示的是一个窗口对象,一个窗口下可以有多个文档对象。
    所以一个窗口下只有一个window.location.href,然则可能有多个document.URL、document.location.href
  17. window.location.href和document.location.href可以被赋值,然后跳转到其它页面,document.URL只能读不克不及写

 

JavaScript获取当前url根目录(路径)