javascript获取地址栏参数的二种方法

发布时间:2019-10-29编辑:脚本学堂
javascript获取地址栏中传递的参数,这里介绍二个方法,字符串分割法与正则分析法,供大家学习参考。

1、字符串分割分析法
可以获取URL+?带QUESTRING参数,相当于asp的request.querystring,PHP的$_GET,代码简洁实用。

<script>
function GetRequest()
{
var url = location.search; //获取url中"?"符后的字串
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.split("=")[0]]=unescape(strs.split("=")[1]);
    }
}
return theRequest;
}
</script>

调用示例:
 

<script>
var Request=new Object();
Request=GetRequest();
var 参数1,参数2,参数3,参数N;
参数1=Request['参数1'];
参数2=Request['参数2'];
参数3=Request['参数3'];
参数N=Request['参数N'];
</script>

以此获取url串中所带的同名参数

二、正则分析法
 

function  GetQueryString(name)   
{   
     var     reg     =   new   RegExp("(^|&)"+     name     +"=([^&]*)(&|$)");   
     var     r     =     window.location.search.substr(1).match(reg);   
     if     (r!=null)   return     unescape(r[2]);   return   null;   
}   
alert(GetQueryString("参数名1"));   
alert(GetQueryString("参数名2"));   
alert(GetQueryString("参数名3"));
function fQueryString(sKey, bDecode, sLocationSearch, bDebug)
{/* shawl.qiu code, return string */
var Debug = bDebug;
if(!sLocationSearch) sLocationSearch = location.search;
if(!sKey) return sLocationSearch;

var sTemp = sLocationSearch.replace(/^?/,"");
if(Debug) alert(sTemp);

if(sTemp==""&&bDebug) throw new Error("页面 sLocationSearch 没有查询参数!"); 
var Ar = sTemp.split("&"), sFinal = ""; 
var iArLen = Ar.length, iArCount = 0;
//by www.jb200.com
while(iArCount++<iArLen)
{
  if(Debug)
  {
   alert("Ar[iArCount-1].toLowerCase(): "+Ar[iArCount-1].toLowerCase());
   alert("sKey.toLowerCase()+'=': "+sKey.toLowerCase());
  }
  
  var arQsByPart = Ar[iArCount-1].split("=");
  if(arQsByPart[0].toLowerCase()==sKey.toLowerCase())
  {
   if(arQsByPart.length==1) continue;
   
   sFinal = arQsByPart[1];
   if(bDecode) sFinal = decodeURI(sFinal);
   break;
  }
}/* end while(iArCount++iArLen) */

if(sFinal==""&&bDebug) throw new Error("没有键为 "+sKey+" 的查询参数!");

return sFinal;
}/*end */