问题
I'm trying to call my servlet GET method and pass value from html select by using onChange. So far I have something like this.
<form name="form1" action="http://localhost:8080/MainServlet/main" method="GET">
<input type=hidden name="action" value="checking">
<div class="select123" onchange="javascript:document.form1.submit();">
<select>
<option selected="" value=""></option>
<option value="">1</option>
<option value="">2</option>
<option value="">3</option>
<option value="">4</option>
</select>
</div>
<br><br>
</form>
I am able to access servlet but when I try to read my select123 value, it is null.
How can I correct it?
回答1:
Couple of issues in your code.
1. There is no value in options value attribute all blank. Have some values there.
2. The html should be something like this:-
<div>
<select name="select123" onchange="javascript:document.form1.submit();">
<option selected="" value=""></option>
<option value="">1</option>
<option value="">2</option>
<option value="">3</option>
<option value="">4</option>
</select>
</div>
There is going to be no change in div and class attribute cannot be used to not access value in servlet you have define the name attribute.
You can access the value in servlet like below
String selectedValue = request.getParameter("select123");
回答2:
How can I correct it?
Modify the code
<form name="form1" action="/MainServlet/main" method="POST">
<input type="hidden" name="action" value="checking">
<div class="select123">
<select name="select123" onchange="document.form1.submit();">
<option selected="selected" value=""></option>
<option value="">1</option>
<option value="">2</option>
<option value="">3</option>
<option value="">4</option>
</select>
</div>
<br><br>
</form>
来源:https://stackoverflow.com/questions/31099969/call-servlet-from-select-onchange-and-pass-value