Home > Web Front-end > JS Tutorial > body text

在JavaScript中获取请求的URL参数[正则]_javascript技巧

WBOY
Release: 2016-05-16 18:13:21
Original
1073 people have browsed it

第一种方法:,代码比较专业 推荐

复制代码 代码如下:

<script> <BR>function GetLocationParam(param){ <BR>var request = { <BR>QueryString : function(val) { <BR>var uri = window.location.search; <BR>var re = new RegExp("" +val+ "=([^&?]*)", "ig"); <BR>return ((uri.match(re))?(decodeURI(uri.match(re)[0].substr(val.length+1))):''); <BR>} <BR>} <BR>return request.QueryString(param); <BR>} <BR>var uid=GetLocationParam("uid"); <BR></script>

第二种方法:
当然我们可以在后台中获取参数的值,然后在前台js代码中获取变量的值,具体做法请参考我的这篇文章:JavaScript获取后台C#变量以及调用后台方法。

其实我们也可以直接在js中获取请求的参数的值,通过使用window.location.search可以获取到当前URL的?号开始的字符串,如前面的链接获取到的search为?id=001。再对获取的字符串进行处理,就可以获取到参数的值了。
复制代码 代码如下:

function getUrlParam(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if (r != null)
return unescape(r[2]);
return null;
}

在调用上面的方法的时候,只要传入参数的名称,就可以获取到你想要的参数的值了,如:getUrlParam("id")。
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!