繁体   English   中英

如何在URL中获取第一个查询字符串的值

[英]How can i get the value of first query string in a URL

您好我使用以下代码来获取表单字段中的查询字符串值:

<script>
var url = window.location.search;
url = url.replace("?Id=", ''); // remove the ? 
</script>
<script>document.write("<input name='Id' data-constraints='@Required(groups=[customer])' id='Id' type='text' value='"+url+"' />");</script>

如果我访问[这不是链接]( http://mydomain.com/?Id=987 )它会在字段中记录Id,但是当包含更多参数时,它也会记录在字段中,我只想要第一个或任何特定的要在表单字段中添加查询字符串参数?

如何使用查询字符串参数构建一个漂亮的小关联数组,如:

var urlParams = [];
window.location.search.replace("?", "").split("&").forEach(function (e, i) {
    var p = e.split("=");
    urlParams[p[0]] = p[1];
});

// We have all the params now -> you can access it by name
console.log(urlParams["Id"]);

基本上,您需要检查是否存在&符号,将子字符串添加到&符号。

您可以在执行替换后添加此代码:

var start = url.indexOf('&');

if(start > 0) {
    url = url.substring(0, start);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM