日期:2014-05-16  浏览次数:20302 次

js获得地址栏参数,实现getParameter(),getParameterValues() 方法
//js构建HashMap
 function HashMap(key,value){
    var key;
    var value;
    this.put = function(key,value){
    this.key = key;
    this.value = value;
  }
  this.getKey = function(){
  return key;
  }
  this.getValue = function(){
   return value;
  }
 }

 //构建简单对象
  function Request(){
  var parameters = null;
  this.init = function(){
    var location = window.location.href;
    var index = location.indexOf("?");
    var queryString = ((index>0)?location.substring(index+1):null);
    if(null!=queryString){
       parameters = new Array();
       var parameterArray = queryString.split("&");
       var length = parameterArray.length;
       for(var i=0;i<length;i++){
       var parameter = parameterArray[i];
       index =  parameter.indexOf("=");
       var key = parameter.substring(0,index);
       var value = parameter.substring(index+1);
       if(null!=key && key.length>0){
         parameters.push(new HashMap(key,value));
      }
     }
    }
  }

  this.getParameter = function(key){
  this.init();
  if(null==parameters)
    return "";
  var length = parameters.length;
  for(var i=0;i<length;i++){
     hashMap = parameters[i];
     if(hashMap.getKey() == key){
       return hashMap.getValue();
     }
   }
   return "";
 }
 
 this.getParameterValues = function(key){
  this.init();
  if(null==parameters)
    return null;
  var array = new Array();
  var length = parameters.length;
  for(var i=0;i<length;i++){
      hashMap = parameters[i];
      if(hashMap.getKey() == key){
        array.push(hashMap.getValue());
     }
  }
  return array;
  }
 }

//用法 
new Request().getParameter(key) 返回string
new Request().getParameterValues(key) 返回array