獲取當前頁面url信息


下面我們舉例一個URL,然后獲得它的各個組成部分:http://localhost:8000/#/index/cardinfo?_k=0wnq36

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

var integrityurl = window.location.href;
console.log(integrityurl);
返回:http://localhost:8000/#/index/cardinfo?_k=0wnq36

2、window.location.protocol(設置或獲取 URL 的協議部分)

var example = window.location.protocol;
console.log(example);
返回:http:

3、window.location.host(設置或獲取 URL 的主機部分)

var example = window.location.host;
console.log(example);
返回:localhost:8000

4、window.location.port(設置或獲取與 URL 關聯的端口號碼)

var example = 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 的路徑部分(就是文件地址))
var example = window.location.pathname;
console.log(example);
返回:/(獲取的是域名后的第一個 “/” 與 “ / ”后面內容)

  例如:url 為這個類型的時候:https://i.cnblogs.com/EditPosts.aspx?opt=1
  返回:/EditPosts.aspx

6、window.location.search(設置或獲取 href 屬性中跟在問號后面的部分)

var example = window.location.search;
console.log(example);
返回:?_k=0wnq36

PS:獲得查詢(參數)部分,除了給動態語言賦值以外,我們同樣可以給靜態頁面,並使用javascript來獲得相信應的參數值。

7、window.location.hash(設置或獲取 href 屬性中在井號“#”后面的分段)

var example = 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'];

 


免責聲明!

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



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