Reputation: 3416
I have this code
<%=out.write("<input
type=\"hidden\"
id=\"tid\"
value=\""+request.getParameter("id").toString()+"
\"/>")%>
<script type="text/javascript">
getPage(document.getElementById("tid").value)
</script>
This code creates a hidden field with the value came from
<site root>/viewPage.jsp?id=erwdf
url and pass the value of this hidden field to a jsp function. When I ran this code on Tomcat it gave an error as
The method print(boolean) in the type JspWriter is not applicable for the arguments (void)
on JSP code line I given above. So am I doing anything wrong or is there any alternative method to pass a GET parameter to a JavaScript function? I don't know much about Javascript just started to learn it.
Upvotes: 1
Views: 14134
Reputation: 1109745
Why so overcomplicated with a hidden field?
Just do
getPage('<%=request.getParameter("id")%>');
Or easier, with EL
getPage('${param.id}');
You may only want to escape special JS characters by Apache Commons Lang StringEscapeUtils
, otherwise the generated JS code may break whenever the parameter value contains a single quote or any other special JS character.
getPage('<%=StringEscapeUtils.escapeJavaScript(request.getParameter("id"))%>');
Or when in EL
getPage('${util:escapeJS(param.id)}');
Upvotes: 3
Reputation: 8961
I believe you meant <%out.write
instead of <%=out.write
about the other issue from the comments, this will assist with getPage and perform escaping of quotes, other special chars...
<script type="text/javascript">
getPage("<% try {
out.write(URLEncoder.encode(request.getParameter("id").toString(), "UTF-8"));
} catch (Exception e) {
} %>")
</script>
Upvotes: 2
Reputation: 3654
You don't have to store it in a hidden field to access it from js. You can read it from the documents location. I personally use a method like this to grab GET parameters from my url.
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
var id = getUrlVars()['id'];
Upvotes: 2