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="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="<%=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只能讀不克不及寫

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM