Javascript 获取Request请求参数实现

来源:互联网 发布:mac os 照片 文件夹 编辑:程序博客网 时间:2024/05/07 10:39
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;}

测试用例:

@Testpublic 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"));}


原创粉丝点击