码迷,mamicode.com
首页 > 编程语言 > 详细

javascript获取url传参

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

标签:string   split   ret   match   com   nbsp   new   regex   location   

方法一:

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

标签:string   split   ret   match   com   nbsp   new   regex   location   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!