如何在javascript中从url获取参数值?
可能重复:如何在javascript中从url获取参数值?,javascript,url,Javascript,Url,可能重复: 我有一个如下的url http://localhost/xxx.php?tPath=&pid=37 http://localhost/xxx.php?tPath=&action=xxx&pid=37&value=13&fname=aaaa&fone=4321122 我想得到pid=37,但它的名字,因为在时间的url是如上所述,然后当页面刷新,然后url变成如下所示 http://localhost/xxx.php?tPath=&
我有一个如下的url
http://localhost/xxx.php?tPath=&pid=37
http://localhost/xxx.php?tPath=&action=xxx&pid=37&value=13&fname=aaaa&fone=4321122
我想得到pid=37,但它的名字,因为在时间的url是如上所述,然后当页面刷新,然后url变成如下所示
http://localhost/xxx.php?tPath=&pid=37
http://localhost/xxx.php?tPath=&action=xxx&pid=37&value=13&fname=aaaa&fone=4321122
所以我想得到pid=37。它可能是一个函数,我将pid作为参数传递给它,它返回它的值
如何执行此操作?使用以下功能
function getParameterValue(name)
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null ) return "";
else return results[1];
}
查看或遵循以下解决方案:
function getParam( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
var frank_param = getParam( 'pid' );
检查这个小实用程序
用法:
var up = new URLParser();
var urlObj = up.parse('http://localhost/xxx.php?tPath=&action=xxx&pid=37&value=13&fname=aaaa&fone=4321122');
alert(urlObj.params['fname']); //alerts 'aaaa'
urlObj的值:
baseURL: "http://localhost/xxx.php"
params:{
action: "xxx"
fname: "aaaa"
fone: "4321122"
pid: "37"
tPath: ""
value: "13"
}
queryString: "tPath=&action=xxx&pid=37&value=13&fname=aaaa&fone=4321122"
嗯,已经有三个答案了,它们都使用正则表达式。但是正则表达式对于这项工作来说确实是错误的工具。正如有人所说,有些人在遇到问题时会想,“我知道,我会使用正则表达式!”现在他们有两个问题。以下是这些答案错误的一些原因:
- 如果要查找的“名称”中包含正则表达式字符,则需要对其进行转义,如果URL在路径部分使用了符号,则所有正则表达式都会失败(不符合RFC,但有些人可能会这样做)
- 如果您要查找的参数包含在正则表达式中有意义的字符(例如,
),则所有参数都会失败$
- 哦,而且它们都无法解释多个结果(例如,path?foo=bar&foo=baz),这在查询字符串中非常有效且相对常见
这实际上是纯ol'字符串函数的作业,如中所示。我可能会以不同的风格编写函数,但算法是合理的。请看以下答案:本文的答案可以帮助您。这对我有用