3

下面是我的代码(1.jsp)

<html>
<head>
  <script type="text/javascript">

   function changeFunc() {
var selectBox = document.getElementById("selectBox");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
  document.write("\n value is"+selectedValue);
  }

 </script>
</head>
 <body>
<form method="post" action="SampServlet">
  <select id="selectBox" name="selurl" onchange="changeFunc();">
   <option value="1">Option #1</option>
   <option value="2">Option #2</option>
  </select>
</form>
 </body>
</html>

在这里,我已将此代码插入到一个 jsp 页面中。并像这样在同一个 jsp 中将“selectedValue”的值从 javascript 获取到 scriptlet。

<% String val=(String)request.getParameter("selurl");
System.out.println("\n selected value is:"+val); %>

我将选定的值作为空值作为输出。如果我打印 javascript selectedValue 参数,它会给我正确的输出,即输出作为选择的选项。但在 scriptlet 中,我得到了 null。错误在哪里。我包括了所有标题和指令。请帮助我。

4

4 回答 4

2

使用提交按钮在同一页面获取您选择的值,不需要任何功能,不需要提交。

例如:

<form method="post" action="">
 <select id="selectBox" name="selurl">
<option value="1">Option #1</option>
<option value="2">Option #2</option>
</select>
<input type="submit" value="Submit" name="sub">
                                                //use scriplet tag 
<% String r=request.getParameter("sub");
if(r.equals("Submit"){
String s=request.getParameter("selurl");
System.out.println("selected value is "+s);
}%>
</form>
于 2014-02-06T12:01:44.160 回答
2

在您的网络浏览器中,您只有 html、javascript 和 css。所有 JSP 代码都应该在服务器上运行。所以你只得到jsp文件的输出。在此之后,您将无法更改 jsp 代码。

于 2013-05-20T06:35:17.943 回答
0

你错过了<submit>按钮。

<form method="post" action="SampServlet">
  <select id="selectBox" name="selurl" onchange="changeFunc();">
   <option value="1">Option #1</option>
   <option value="2">Option #2</option>
  </select>
  <input type="submit" /> <!-- MISSING!! -->
</form>

添加按钮并单击它以将表单提交到您的 servlet,并将所选值发送为selurl. 请注意,您的表单action属性指向的SampServlet似乎是一个 servlet。action="page.jsp"对于 jsps,我们通常在表单中有类似的东西。

编辑
如果您想在用户从下拉列表中选择一个值时自动发布表单,只需将您设置onchange为:(您甚至不需要<submit>按钮)

onchange="this.form.submit()"
于 2013-05-20T06:43:46.963 回答
0

您的 select 元素应该有一个 name 属性,并且您必须在 request.getParameter() 中使用该名称

<select id="selectBox" name="selurl"">
   <option value="1">Option #1</option>
   <option value="2">Option #2</option>
</select>


String val = request.getParameter("mySelect");

编辑:

如果您希望在 select 元素的 onchange 事件上发出服务器请求,则必须使用 Ajax。

使用 jQuery,

$.post('SampServlet', {selectedValue: selectedValue}, function(data) {
//Update view
});
于 2013-05-20T06:35:25.950 回答