獲取和添加URL地址欄參數


URL地址(添加參數:傳參)

js寫法:
//1.window.location.href
var a ="1018802,8"
var b ="1"
window.location.href="../EditPosts.aspx?postid="+a+"&update="+b;

//2.字符串模板,動態生成href屬性
var c = '<a class=" " href="../EditPosts.aspx?postid=\''+a+'\')">查看地址</a>'

URL地址(獲取參數:取參)

1.只使用split將字符串截取成數組
var url=window.location.href
var pars=url.split("?")[1].split("=")[1].split(",")[1];

//例如 https://i.cnblogs.com/EditPosts.aspx?postid=1018802,8&update=1
//執行到split("?")[1]  =>  "postid=1018802,8&update=1"
//執行到split("&")[1]  =>  "1018802,8&update"
//執行到split(",")  =>  ["1018802,8","update"]
//執行到split(",")[1]  =>  "1018802,8"

反復截取,有點繁瑣哎~

2.字符串拆分法

window.location.href 或者 location.href 或者 window.location 獲得地址欄中的所有內容

decodeURI()可以解碼地址欄中的數據 恢復中文數據

window.search 獲得地址欄中問號及問號之后的數據

//獲取地址欄里(URL)傳遞的參數  
function GetRequest(value) {  
    //url例子:www.bicycle.com?id="123456"&Name="bicycle";  
    var url = decodeURI(location.search); //?id="123456"&Name="bicycle";
    var object = {};
    if(url.indexOf("?") != -1)//url中存在問號,也就說有參數。  
    {   
      var str = url.substr(1);  //得到?后面的字符串
      var strs = str.split("&");  //將得到的參數分隔成數組[id="123456",Name="bicycle"];
      for(var i = 0; i < strs.length; i ++)  
        {   
        object[strs[i].split("=")[0]]=strs[i].split("=")[1]
      }
  }
    return object[value];  
}  
3.正則匹配法

這種方法其實原理和上一種方法類似,都是從URL中提取,只是提取的方法不同而已。

function GetQueryString(name) {  
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");  
    var r = window.location.search.substr(1).match(reg);  
    if (r != null) {   
        return unescape(r[2]);  
    }  
    return null;  
} 
4.在vue中可以通過this.$route獲取路由對象然后根據具體需要取對象內容
this.$route.path 當前頁面路由
this.$route.params 路由參數
this.$route.query 查詢路由參數


免責聲明!

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



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