js实现获取url问号后参数,第一步封装方法获取?后所有字符,并根据&=符号获取单个或多个参数及参数值

getParams() {
  var url = location.search;
  var params = new Object();
  if (url.indexOf("?") != -1) {
    const str = url.substr(1);
    const strs = str.split("&");
    for (var i = 0; i < strs.length; i++) {
      params[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
    }
  }
  return params;
}
方法写好后直接调用方法获取url。其中 urlParams['参数名'],如果参数名写错会获取不到此参数值。例:http:172.17.10.0:8080?id=123&name=张三,使用:urlParams['id'],urlParams['name']
console.log(window.location.search)
var urlParams = new Object();
urlParams = this.getParams();
this.id = urlParams['id'];   //要获取的参数名
this.name = urlParams['name'];   //要获取的参数名
console.log(this.id, this.name)

瑞瑞_
73 声望8 粉丝