如何在同一个JSP页面中从javascript代码获取值到JSP scriptlet

how to get the value from javascript code to jsp scriptlet with in the same jsp page

本文关键字:JSP 获取 javascript 代码 scriptlet 同一个      更新时间:2023-09-26

下面是我的代码(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中,从javascript到scriptlet获取"selectedValue"的值,就像这样。
<% String val=(String)request.getParameter("selurl");
System.out.println("'n selected value is:"+val); %>

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

在你的浏览器中只有html, javascript和css。所有JSP代码都要在服务器上运行。因此,您只能得到jsp文件的输出。在此之后,您不能更改jsp代码。

使用submit按钮在同一页面和不需要任何函数,不需要onsubmit

例如:

<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>

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
});

您缺少<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。对于jsp,我们通常有action="page.jsp"这样的格式。

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

onchange="this.form.submit()"