DIV CSS 佈局教程網

JavaScript 獲取當前頁面 URL 各組成部分的完整總結
編輯:關於JavaScript     

Web 開發中經常需要從當前頁面地址裡取信息,比如判斷路由、解析參數、做分享統計。這裡把 location 對象的相關屬性系統整理一遍。

先準備一個示例 URL:

 https://i.cnblogs.com/EditPosts.aspx?opt=1

location 的常用屬性

1、window.location.href——設置或獲取整個 URL 字符串

 var test = window.location.href; alert(test); // https://i.cnblogs.com/EditPosts.aspx?opt=1

2、window.location.protocol——協議部分

 var test = window.location.protocol; alert(test); // http:

3、window.location.host——主機部分,包含端口

 var test = window.location.host; alert(test); // i.cnblogs.com

4、window.location.port——端口號

 var test = window.location.port; alert(test); // 空字符串

注意:採用默認 80 端口時,即使地址裡手寫了 :80,返回值依然是空字符串。

5、window.location.pathname——路徑部分,也就是文件地址

 var test = window.location.pathname; alert(test); // /EditPosts.aspx

6、window.location.search——問號後面的查詢串

 var test = window.location.search; alert(test); // ?opt=1

補充一句:查詢參數並不是動態語言的專利,靜態頁面同樣可以帶參數,用 JS 取值即可。

7、window.location.hash——井號後面的片段

 var test = window.location.hash; alert(test); // 空字符串(示例 URL 中沒有)

如何取 URL 中的參數值

方法一:正則匹配

 function getQueryString(name) { var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i'); var r = window.location.search.substr(1).match(reg); if (r != null) { return unescape(r[2]); } return null; } // 這樣調用: alert(GetQueryString("參數名1")); alert(GetQueryString("參數名2")); alert(GetQueryString("參數名3"));

正則裡的 (^|&) 和 (&|$) 用來卡住參數名的邊界,避免把 otherid 誤匹配成 id。

方法二:split 拆分

 function GetRequest() { var url = location.search; //獲取url中"?"符後的字串 var theRequest = new Object(); if (url.indexOf("?") != -1) { var str = url.substr(1); strs = str.split("&"); for(var i = 0; i < strs.length; i ++) { theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]); } } return theRequest; } var Request = new Object(); Request = GetRequest();<br>// var id=Request["id"]; // var 參數1,參數2,參數3,參數N; // 參數1 = Request['參數1']; // 參數2 = Request['參數2']; // 參數3 = Request['參數3']; // 參數N = Request['參數N'];

這種寫法的好處是一次性把所有參數收進對象,後續取值很方便。

方法三:只取指定的一個

 function GetQueryString(name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); var r = window.location.search.substr(1).match(reg); //獲取url中"?"符後的字符串並正則匹配 var context = ""; if (r != null) context = r[2]; reg = null; r = null; return context == null || context == "" || context == "undefined" ? "" : context; } alert(GetQueryString("j")); 

這裡多了一層空值過濾,把 null、空串和字符串 "undefined" 統一歸為空,能省掉不少判空麻煩。

方法四:已知只有一個參數時

 function GetRequest() { var url = location.search; //獲取url中"?"符後的字串 if (url.indexOf("?") != -1) { //判斷是否有參數 var str = url.substr(1); //從第一個字符開始 因為第0個是?號 獲取所有除問號的所有符串 strs = str.split("="); //用等號進行分隔 (因為知道只有一個參數 所以直接用等號進分隔 如果有多個參數 要用&號分隔 再用等號進行分隔) alert(strs[1]); //直接彈出第一個參數 (如果有多個參數 還要進行循環的) } }

參數個數確定的情況下,這樣寫最省事,不用引入正則也不必循環。

以上就是關於獲取當前頁面 URL 信息的全部整理,希望對你有所幫助。

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