首页 > 编程语言 > 详细

javascript获取url传参

时间:2017-03-13 11:11:44      阅读:234      评论:0      收藏:0      [点我收藏+]

方法一:

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传参

原文:http://www.cnblogs.com/llws/p/6541650.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!