js 获取url传参

js代码:

<Script language="javascript">   
function GetRequest() {   
   var url = location.search;    
   var theRequest = new Object();   
   if (url.indexOf("?") != -1) {   
      var str = url.substr(1);   
      strs = str.split("&");   
      for(var i = 0; i < strs.length; i ++) {   
         theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);   
      }   
   }   
   return theRequest;   
}

正则:

function GetRequest(name)
        {
             var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
             var r = window.location.search.substr(1).match(reg);
             if(r!=null)return  unescape(r[2]); return null;
        }

如果有汉字以上方法的返回结果会出现乱码,可以使用decodeURI和encodeURI解决

window.href = http://www....?name='+encodeURI(store_name)
        function GetRequest(name)
{
     var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
     var r = window.location.search.substr(1).match(reg);
     if(r!=null)return  decodeURI(r[2]); return null;
}

猜你喜欢

转载自www.cnblogs.com/fangling/p/9220086.html