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

JavaScript js获取地址栏里传递的参数

字符串分割分析法。
这里是一个获取url+?带questring参数的javascript客户端解决方案,相当于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;

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 function fquerystring */ 本文链接:js获取地址栏里传递的参数?