1. 程式人生 > >JS 獲得當前位址列url

JS 獲得當前位址列url

URL即:統一資源定位符 (Uniform Resource Locator, URL) 
完整的URL由這幾個部分構成: 
scheme://host:port/path?query#fragment 
scheme:通訊協議 
常用的http,ftp,maito等 

host:主機 
伺服器(計算機)域名系統 (DNS) 主機名或 IP 地址。 

port:埠號 
整數,可選,省略時使用方案的預設埠,如http的預設埠為80。 

path:路徑 
由零或多個"/"符號隔開的字串,一般用來表示主機上的一個目錄或檔案地址。 

query:查詢 
可選,用於給動態網頁(如使用CGI、ISAPI、PHP/JSP/ASP/ASP.NET等技術製作的網頁)傳遞引數,可有多個引數,用"&"符號隔開,每個引數的名和值用"="符號隔開。 

fragment:資訊片斷 
字串,用於指定網路資源中的片斷。例如一個網頁中有多個名詞解釋,可使用fragment直接定位到某一名詞解釋。(也稱為錨點.) 

對於這樣一個URL 

http://www.x2y2.com:80/fisker/post/0703/window.location.html?ver=1.0&id=6#imhere 


我們可以用javascript獲得其中的各個部分 
1, window.location.href 
整個URl字串(在瀏覽器中就是完整的位址列) 
本例返回值: http://www.x2y2.com:80/fisker/post/0703/window.location.html?ver=1.0&id=6#imhere 

2,window.location.protocol 
URL 的協議部分 
本例返回值:http: 

3,window.location.host 
URL 的主機部分 
本例返回值:www.x2y2.com 

4,window.location.port 
URL 的埠部分 
如果採用預設的80埠(update:即使添加了:80),那麼返回值並不是預設的80而是空字元 
本例返回值:"" 

5,window.location.pathname 
URL 的路徑部分(就是檔案地址) 
本例返回值:/fisker/post/0703/window.location.html 

6,window.location.search 
查詢(引數)部分 
除了給動態語言賦值以外,我們同樣可以給靜態頁面,並使用javascript來獲得相信應的引數值 
本例返回值:?ver=1.0&id=6 

7,window.location.hash 
錨點 
本 例返回值:#imhere 那麼就可以用這個方法取到指定引數: function hooyesQueryString(queryStringName){ var returnValue=""; var URLString=new String(document.location); var serachLocation=-1; var queryStringLength=queryStringName.length; do { serachLocation=URLString.indexOf(queryStringName+"\="); if (serachLocation!=-1) { if ((URLString.charAt(serachLocation-1)=='?') || (URLString.charAt(serachLocation-1)=='&')) { URLString=URLString.substr(serachLocation); break; } URLString=URLString.substr(serachLocation+queryStringLength+1); } } while (serachLocation!=-1) if (serachLocation!=-1) { var seperatorLocation=URLString.indexOf("&"); if (seperatorLocation==-1) { returnValue=URLString.substr(queryStringLength+1); } else { returnValue=URLString.substring(queryStringLength+1,seperatorLocation); } } return returnValue;}然後:hooyesQueryString("id")就取到id引數的值