Js獲取當前頁面地址參數


1,獲取當前窗口的url;  結果:http://localhost:61768/Home/Index?id=2&age=18

  var url = window.location.href;

2,獲取當前窗口的主機名;   結果:localhost:61768

      var host = window.location.host;

3,獲取當前窗口的端口; 結果:61768

      var port = window.location.port;

4,獲取當前窗口的路徑 ; 結果:/Home/Index

    var pathname = window.location.pathname;

5,獲取當前文檔的Url;結果:http://localhost:61768/Home/Index?id=2&age=18

    var URL = document.URL;

6,獲取參數;結果:?id=2&age=18

    var search = window.location.search;

7,設置或獲取 URL 的協議部分;結果:http

    var protocol = window.location.protocol

8,設置或獲取 href 屬性中在井號“#”后面的分段

  var hash = window.location.hash

 

分割url提取參數

var search = window.location.search;
var age = getSearchString('age', search); //結果:18
var id = getSearchString('id', search); //結果:2
//key(需要檢索的鍵) url(傳入的需要分割的url地址,例:?id=2&age=18)
function getSearchString(key, Url) {
    var str = Url;
    str = str.substring(1, str.length); // 獲取URL中?之后的字符(去掉第一位的問號)
    // 以&分隔字符串,獲得類似name=xiaoli這樣的元素數組
    var arr = str.split("&");
    var obj = new Object();
    // 將每一個數組元素以=分隔並賦給obj對象
    for (var i = 0; i < arr.length; i++) {
        var tmp_arr = arr[i].split("=");
        obj[decodeURIComponent(tmp_arr[0])] = decodeURIComponent(tmp_arr[1]);
    }
    return obj[key];
}

 

原文鏈接:https://www.cnblogs.com/qianxundaozhu/p/11584900.html


免責聲明!

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



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