1. 程式人生 > >js 獲取url傳參

js 獲取url傳參

ref col js代碼 clas The mat indexof www. In

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; }

js 獲取url傳參