乐趣区

关于前端:js获取url问号后参数

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)
退出移动版