检索查询字符串参数的简便方法 [英] Elegant way of retrieving query string parameter

查看:130
本文介绍了检索查询字符串参数的简便方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在检索一个查询字符串参数,为此,我的代码是

I am retrieving one query string parameter, and for that my code is

 <a href="Default2.aspx?Id=1&status=pending&year=2010">Click me</a>

现在,我要检索"status = pending",为此,我正在这样做

Now I want to retrieve "status=pending" and for that I am doing

 var qString = window.location.search.substring(1);
                  var Keys = qString .split('&');
                 alert(Keys[1]);

这很好用,但是我在这里将[1]硬编码.没有硬编码就能做到这一点吗?

This works fine, but I am hard-coding [1] here. is there any elegent way of doing this without hard-coding?

推荐答案

我将使用正则表达式,例如:

status=([a-zA-Z])+

这只会检索状态是什么.如果您已经知道变量始终称为状态,但不知道值是什么,那么这就是正确的方法.

This will retrieve only what the status is. If you already know the variable is always called status, but don't know what the value is, this is the right way to go.

要使用它,您必须执行以下操作:

To use it, you'd have to do something like this:

var qString = window.location.search.substring(1);
qString.match(/status=([a-zA-Z])+/);

希望有帮助

这篇关于检索查询字符串参数的简便方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆