【问题标题】:how to get the parameter value from the url in javascript? [duplicate]如何从javascript中的url获取参数值? [复制]
【发布时间】:2012-03-31 21:30:41
【问题描述】:

可能重复:
How can I get a specific parameter from location.search?

我有一个类似下面的网址。

http://localhost/xxx.php?tPath=&pid=37

我想得到 pid=37 但它的名字,因为按时 url 就像上面一样,然后当页面刷新时,url 变成如下所示。

http://localhost/xxx.php?tPath=&action=xxx&pid=37&value=13&fname=aaaa&fone=4321122

所以我想得到 pid=37。它可能是一个函数,我将 pid 作为参数传递给它并返回它的值。

我该怎么做?

【问题讨论】:

标签: javascript url


【解决方案1】:

查看this 或遵循以下解决方案:

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' );

【讨论】:

  • 这对我有用
【解决方案2】:

使用下面的函数

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

【讨论】:

    【解决方案3】:

    嗯,已经有三个答案,它们都使用正则表达式。但是正则表达式对于这项工作来说确实是错误的工具。就像有人说的那样,有些人在遇到问题时会想,“我知道,我会使用正则表达式!”现在他们有两个问题。以下是这些答案错误的一些原因:

    • 如果您要查找的“名称”中包含正则表达式字符,则需要对其进行转义,并且如果 URL 在路径部分使用与号(不符合 RFC,但有些人可能还是会这样做)。

    • 如果您要查找的参数包含在正则表达式中有意义的字符(例如,$),它们都会失败。

    • 哦,它们都没有考虑到多个结果(例如,path?foo=bar&foo=baz),这在查询字符串中是完全有效且相对常见的。

    这确实是普通字符串函数的工作,如this answer 中所给出。我会在风格上稍微不同地编写函数,但算法是合理的。

    【讨论】:

      【解决方案4】:

      检查这个小工具http://jsfiddle.net/gwB2C/2/

      用法:

      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"
      

      【讨论】:

        猜你喜欢
        • 2020-09-05
        • 2012-09-17
        • 2021-08-16
        • 2012-07-19
        • 1970-01-01
        • 2010-12-10
        • 1970-01-01
        • 1970-01-01
        • 2018-10-28
        相关资源
        最近更新 更多