JS获取Request请求参数实现

  • Post author:
  • Post category:其他




Javascript版

方法:

String.prototype.getParameter = function (key) {
	var re = new RegExp(key + '=([^&]*)(?:&)?');
    return this.match(re) && this.match(re)[1];
};

测试代码:

<script type="text/javascript">
<!--
String.prototype.getParameter = function (key) {
	var re = new RegExp(key + '=([^&]*)(?:&)?');
    return this.match(re) && this.match(re)[1];
};
var s = "http://www.baidu.com/index.html?x0=0&x1=1&x2=2&x3=3&x4=http://www.google.com";
document.write(s.getParameter('x0') + "<br/>");
document.write(s.getParameter('x1') + "<br/>");
document.write(s.getParameter('x2') + "<br/>");
document.write(s.getParameter('x3') + "<br/>");
document.write(s.getParameter('x4') + "<br/>");
document.write(s.getParameter('undefined') + "<br/>");
//-->
</script>

输出:

0
1
2
3
http://www.google.com
null



java版

方法:

public static String getParameter(String url, String key) {
	Pattern pat = Pattern.compile("[&?]+" + key + "=([^&]*)&?");
	Matcher mat = pat.matcher(url);
	if(mat.find()){
		return mat.group(1);
	}
	return null;
}

测试用例:

@Test
public void testGetParameter() {

	String url = "http://192.168.11.117/ganglia/graph.php?z=xlarge&c=test&h=192.168.11.139&m=cpu_idle&cs=03%2F22%2F2014+00%3A00&ce=03%2F23%2F2014+12%3A00";
	System.out.println(GetParameterTest.getParameter(url, "c"));
	System.out.println(GetParameterTest.getParameter(url, "h"));
	System.out.println(GetParameterTest.getParameter(url, "zxxx"));
	System.out.println(GetParameterTest.getParameter(url, "ce"));

}



版权声明:本文为qq_34845394原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。