首页 > 代码库 > javascript获取url传参

javascript获取url传参

方法一:

function getQueryString(key) {
  var reg = new RegExp("(^|[?&])" + key+ "=([^&]*)(&|$)", "i");
  // var r = window.location.href.substr(1).match(reg);
  var r = "http://www.examples.com?key=123&name=whh&age=26&sex=1&tall=170".substr(1).match(reg);
  return (r != null) ? unescape(r[2]) : null;
}

// 调用方法
console.log(‘name:‘ + getQueryString("name"));
console.log(‘age:‘ + getQueryString("age"));
console.log(‘sex:‘ + getQueryString("sex"));
console.log(‘tall:‘ + getQueryString("tall"));
console.log(‘key:‘ + getQueryString("key"));
console.log(‘hello:‘ + getQueryString("hello"));

 

 

方法二:

function getRequest() {
  // var url = window.location.href; //获取url中"?"符后的字串
  var url = "http://www.examples.com?key=123&name=whh&age=26&sex=1&tall=170";
  var theRequest = new Object();
  if (url.indexOf("?") != -1) {
    var idx = url.indexOf("?"),
    str = url.substr(idx + 1),
    strs = str.split("&");
    for(var i = 0; i < strs.length; i ++) {
      theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);
    } 
  }
  return theRequest;
}
// 调用方法
console.log(‘name:‘ + getRequest().name);
console.log(‘age:‘ + getRequest().age);
console.log(‘sex:‘ + getRequest().sex);
console.log(‘tall:‘ + getRequest().tall);
console.log(‘key:‘ + getRequest().key);
console.log(‘hello:‘ + getRequest().hello);

javascript获取url传参