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 

給鏈接加id : a href="src/html/description.html?id=變量"


7,window.location.hash 
錨點 
本例返回值:#imhere

那么就可以用這個方法取到指定參數: 

 1 function hooyesQueryString(queryStringName) {
 2         var returnValue = "";
 3         var URLString = new String(document.location);
 4         var serachLocation = -1;
 5         var queryStringLength = queryStringName.length;
 6         do {
 7             serachLocation = URLString.indexOf(queryStringName + "\=");
 8             if (serachLocation != -1) {
 9                 if ((URLString.charAt(serachLocation - 1) == '?') || (URLString.charAt(serachLocation - 1) == '&')) {
10                     URLString = URLString.substr(serachLocation);
11                     break;
12                 }
13                 URLString = URLString.substr(serachLocation + queryStringLength + 1);
14             }
15         }
16         while (serachLocation != -1){
17             if (serachLocation != -1) {
18                 var seperatorLocation = URLString.indexOf("&");
19                 if (seperatorLocation == -1) {
20                     returnValue = URLString.substr(queryStringLength + 1);
21                 } else {
22                     returnValue = URLString.substring(queryStringLength + 1, seperatorLocation);
23                 }
24             }
25             return returnValue;
26         }
27         
28     }

 

然后:hooyesQueryString("id")就取到id參數的值

 

參考:http://www.360doc.com/content/10/0831/14/2923250_50123779.shtml


免責聲明!

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



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