DIV CSS 佈局教程網

JS 取得當前路徑的幾種寫法:從 document.URL 到伺服器端 request 方法
編輯:關於JavaScript     

客戶端:取得目前網址

<script type="text/javascript">
thisURL  = document.URL;
thisHREF = document.location.href;
thisSLoc = self.location.href;
thisDLoc = document.location;
strwrite  = " thisURL: ["  + thisURL  + "]<br />"
strwrite += " thisHREF: [" + thisHREF + "]<br />"
strwrite += " thisSLoc: [" + thisSLoc + "]<br />"
strwrite += " thisDLoc: [" + thisDLoc + "]<br />"
document.write( strwrite );

取得上層與目前視窗資訊

thisTLoc  = top.location.href;
thisPLoc  = parent.document.location;
thisTHost = top.location.hostname;
thisHost  = location.hostname;
strwrite  = " thisTLoc: ["  + thisTLoc  + "]<br />"
strwrite += " thisPLoc: ["  + thisPLoc  + "]<br />"
strwrite += " thisTHost: [" + thisTHost + "]<br />"
strwrite += " thisHost: ["  + thisHost  + "]<br />"
document.write( strwrite );

若頁面不在框架中,top 與 parent 都等於自己,因此這幾行的值會相同。跨域框架情況下,存取上層的 location 會因同源策略而拋出錯誤。

只取檔名部分

tmpHPage  = thisHREF.split( "/" );
thisHPage = tmpHPage[ tmpHPage.length - 1 ];
tmpUPage  = thisURL.split( "/" );
thisUPage = tmpUPage[ tmpUPage.length - 1 ];
strwrite  = " thisHPage: [" + thisHPage + "]<br />"
strwrite += " thisUPage: [" + thisUPage + "]<br />"
document.write( strwrite );

以斜線切分後取最後一段,就是檔名。若網址帶有查詢字串或 hash,檔名會包含這些部分,需另行處理。

伺服器端(JSP)

var url = "<%=request.getRequestURI()%>";
alert(url)

JSP 提供的相關方法:

  • request.getRequestURI():請求的 URI 路徑,不含協定、主機與埠,也不含查詢字串。
  • request.getRequestURL():完整的請求 URL(含協定、主機、埠、路徑),不含查詢字串。
  • request.getQueryString():查詢字串部分(問號後面那一段)。
  • request.getServletPath():對應到 servlet 的路徑部分。

若要組出完整的網路位址,可拼接:

request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getRequestURI()

選擇建議

純前端需求(例如取得目前頁面檔名做為標題)用 location.pathname 或 document.URL 即可;需要伺服器已知的部署路徑(context path)時,用 request.getContextPath() 會比的字串拼接更可靠,尤其當應用程式被部署到非根路徑時。另注意反向代理或 HTTPS 卸載的環境下,getScheme() 與 getServerPort() 回傳的可能是內部值,需配合 X-Forwarded-* 標頭判斷。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved