如何从url中提取参数值?

时间:2015-03-28 16:16:08

标签: javascript jquery html servlets

response.sendRedirect("http://localhost:8080/cse/welcome.html?first=fname&last=lname&dname=dept&mname=mobno");

如何从Url中提取first,last,dname,mname参数,我想在重定向的html文档(welcmoe.html)中使用这些提取的值。我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:0)

如果您希望客户端使用JS,您可以执行以下操作。

//Create an array from query strings
//such as ['first=fname', 'last=lname', ...]
var querystring = location.search.substring(1).split("&");
var props = {};
//Loop thru the array
querystring.forEach(function(item) {
    //split each item
    var item = item.split("=");
    //set the first part as key and last/second part as value
    props[item.shift()] = item.pop();
});
alert ("first: " + props["first"]);
alert ("last: " + props["last"]);
//and so on...

答案 1 :(得分:0)

java servlet中的四个变量可以硬编码并作为字符串传递,如此

StringBuilder url =new StringBuilder();
url.append("http://localhost:8080/cse/welcome.html");
url.append("?first="+fname);
url.append("&last="+lname);
url.append("&dname="+dept);
url.append("&mname="+mobno);
String URL=url.toString();
String urlEncoded=response.encodeRedirectURL(URL);
response.sendRedirect(urlEncoded);

然后可以用这种方式在javascript中获取和调用这些变量

<script>
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var fname = getParameterByName('first');
var lname=getParameterByName('last');
var dept=getParameterByName('dname');
var mobno=getParameterByName('mname');
</script>