Is it possible to assign javascript value to html and use Jsp to get the value?
<html>
<body>
<form action="javascript.jsp">
<script type="text/javascript">
var i = 11;
var j = 12;
<input type="hidden" name="test[0]" value=i />
<input type="hidden" name="test[1]" value=j />
</script>
<input type="image" src="submit.jpg" />
</form>
</body>
</html>
I would like to get t开发者_Python百科he value from the JavaScript variable
and assign the value at array, like <input type="hidden" name="test[0]" value=i />
Then, in server side,
<%! String[] getValue; %>
<%
getValue = request.getParameterValues("test");
if (getValue != null)
{
for (int i = 0; i < getValue.length; i++)
{
out.println ("<b>"+getValue[i]+"<b>");
}
}
%>
But it seems not work.
So, is it possible to assign javascript value to html and use Jsp to get the value?
Or how to modify the code?
Use getElementById
method in javascript to locate elements by their id. and set their value property. Also make sure that code is executed after page has been loaded.
Example:
<html>
<body>
<form action="javascript.jsp">
<input type="hidden" id="test0" />
<input type="hidden" id="test1" />
<script type="text/javascript">
var i = 11;
var j = 12;
window.onload = function()
{
document.getElementById("test0").value = i;
document.getElementById("test1").value = j;
};
</script>
<input type="image" src="submit.jpg" />
</form>
</body>
</html>
On your html page:
<form action="javascript.jsp">
<input type="hidden" name="test0" id="test0" />
<input type="hidden" name="test1" id="test1" />
<input type="image" src="submit.jpg" />
</form>
And somewhere further:
<script type="text/javascript">
var i = 11;
var j = 12;
document.getElementById("test0").value=i;
document.getElementById("test1").value=j;
</script>
Your javascript.jsp then can read this parameters:
<%
out.println(request.getParameter("test0"));
out.println(request.getParameter("test1"));
%>
You was a PHP developer. In PHP the parameter syntax name[]
get converted automagically to a PHP array. This is not standard in HTTP and JSP/Servlet (and many other languages/APIs) doesn't have this "feature".
You have 2 options:
Just give them all the same name.
<input type="hidden" name="test" value="one" /> <input type="hidden" name="test" value="two" /> <input type="hidden" name="test" value="three" />
so that you can use
getParameterValues()
the usual way (the ordering is the same as the elements appear in the HTML DOM tree, this is as per HTTP and HTML specs)String[] tests = request.getParameterValues("test");
Access them by
getParameter()
with the literal nametest[0]
,test[1]
, etc instead.List<String> tests = new ArrayList<String>(); for (int i = 0; i < Integer.MAX_VALUE; i++) { String test = request.getParameter("test[" + i + "]"); if (test != null) { tests.add(test); } else { break; } }
精彩评论