獲取當前頁面URL地址資訊
下面我們舉例一個URL,然後獲得它的各個組成部分:http://localhost:8000/#/index/cardinfo?_k=0wnq36
1、window.location.href(設定或獲取整個 URL 為字串)
varintegrityurl= window.location.href;
console.log(integrityurl);
返回:http://localhost:8000/#/index/cardinfo?_k=0wnq36
2、window.location.protocol(設定或獲取 URL 的協議部分)
varexample= window.location.protocol;
console.log(example
返回:http:
3、window.location.host(設定或獲取 URL 的主機部分)
varexample= window.location.host;
console.log(example);
返回:localhost:8000
4、window.location.port(設定或獲取與 URL 關聯的埠號碼)
varexample= window.location.port;
console.log(example);
返回:8000(如果採用預設的80埠(update:即使添加了:80),那麼返回值並不是預設的80而是空字元)
例如:url 為這個型別的時候:https://i.cnblogs.com/EditPosts.aspx?opt=1
返回:空字元
5、window.location.pathname(設定或獲取與 URL 的路徑部分(就是檔案地址))
varexample= window.location.pathname;
console.log(example);
返回:/(獲取的是域名後的第一個 “/” 與 “ / ”後面內容)
例如:url 為這個型別的時候:https://i.cnblogs.com/EditPosts.aspx?opt=1
返回:/EditPosts.aspx
6、window.location.search(設定或獲取 href 屬性中跟在問號後面的部分)
varexample= window.location.search;
console.log(example
返回:?_k=0wnq36
PS:獲得查詢(引數)部分,除了給動態語言賦值以外,我們同樣可以給靜態頁面,並使用javascript來獲得相信應的引數值。
7、window.location.hash(設定或獲取 href 屬性中在井號“#”後面的分段)
varexample= window.location.hash;
console.log(example);
返回:空字元(因為url中沒有)
8、js獲取url中的引數值
8.1、正則取參
function getUrlParam(name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); var r = window.location.search.substr(1).match(reg); if(r != null) { //return unescape(r[2]); return r[2]; } return null; } //例 console.log(getUrlParam('name'));
8.2、split拆分取參
function getUrlParam() { 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 = getUrlParam(); // var id=Request["id"]; // var 引數1,引數2,引數3,引數N; // 引數1 = Request['引數1']; // 引數2 = Request['引數2']; // 引數3 = Request['引數3']; // 引數N = Request['引數N'];