如何使用javascript或jquery从url参数获取值

如何使用javascript或jquery从url参数获取值,javascript,jquery,Javascript,Jquery,我在从url获取值时遇到了一个问题,我有一个显示模式的链接 像我一样 <a href='#modal?userId=<%=resultSet.getInt("drid")%>' class="button-border toggleModal">Apportionment</a> 现在我想使用javascript获取userId参数的值 <script type="text/javascript"> function getParameterB

我在从url获取值时遇到了一个问题,我有一个显示模式的链接 像我一样

<a href='#modal?userId=<%=resultSet.getInt("drid")%>' class="button-border toggleModal">Apportionment</a>
现在我想使用javascript获取userId参数的值

<script type="text/javascript">

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

var param = getParameterByName("userId");
var userId = document.getElementById("docId");
userId.value = param;


</script>
但无法从中获得价值http://localhost:8080/app/modal?userId=1

发送到服务器的查询字符串必须位于片段标识符之前,该标识符完全由客户端处理

i、 e

如果不想将该数据发送到服务器,则需要读取片段标识符location.hash并在上拆分它?要获得所需的零件。

请使用:

编辑:如果URL为字符串,则可以执行以下操作:

$.url('http://localhost:8080/app/#modal?userId=1').param('userId'); // returns '1'
编辑2:这项工作:

$.url($.url('http://localhost:8080/app/#modal?userId=1').fsegment(1)).param('userId')) //returns '1'

您希望模态在?userId=blah部分之后。关于如何构造URL的更多信息如下:getParameterByName函数不起作用,因为您要查找的数据在片段中,而不是查询字符串中。通常,单页应用程序框架(例如AngularJS)使用这种方法。您是否正在使用这样的框架?如果是这样,它可能会提供方法来检索您需要的信息。@LogicalError-如果您不知道如何拆分javascript字符串,Google会提供帮助。这会解析查询字符串。数据不在查询字符串中。@Quentin:已修复代码。感谢您指出。这是一个问题。一条建议:一些解释将显著提高你答案的质量。
#modal?userId=1
?userId=1#modal
$.url().param('userId');
$.url('http://localhost:8080/app/#modal?userId=1').param('userId'); // returns '1'
$.url($.url('http://localhost:8080/app/#modal?userId=1').fsegment(1)).param('userId')) //returns '1'
function getUrlParams() {   
    var url = window.location
    var inputParam = 'DBName'//input parameter 
    var params = url.split('?');     
    var b = params[1].split('&');   
    for (i=0; i<b.length; i++){
    var c= b[i].split('=');
    if (c[0] == inputParam){
       alert(c[1]);//return the parameter value
       break;
}