【问题标题】:Read selected value of select box and pass it to jsp读取选择框的选定值并将其传递给jsp
【发布时间】:2013-01-13 13:05:39
【问题描述】:

我对 JSP、HTML 等还是很陌生...并且有一个问题:

我有一个 JSP,我正在尝试从 HTML 选择框中读取选定的值,例如使用 JavaScript:

<form name="ListForm" action=""> 
<select name="country" size="6">
<%
    String[] testArray = {"Germany", "Russia", "China", "Iran", "USA", "Israel"};
    for (int i = 0; i < testArray.length; i++) {
%>
        <option value=<%=testArray[i]%>>
        <%= testArray[i] %> 
        </option>
<%
    }
%>
</select> 
</form>

这是 JavaScript:

<script type="text/javascript">
    function getSelectedValue() {
        var e = document.getElementById("country");
        return e.options[e.selectedIndex].text;
    }
</script>

现在我想将此字符串传递给另一个 JSP:

<% 
    String testVar = request.getParameter("country");
    session.setAttribute("varName", testVar); 
%>

但这不起作用。你知道为什么吗?

【问题讨论】:

  • 请从开发人员的角度而非最终用户的角度详细说明“不起作用”。代码似乎也不完整。您无处显示您如何提交表单。所以我认为问题只是你根本没有提交表格。此外,JavaScript 代码不仅被破坏(id 和 name 不一样),而且看起来毫无用处,我想知道它为什么会存在。只需删除该JS代码并将&lt;input type="submit"&gt;添加到&lt;form&gt;并按下它。或者这不是你要问的吗?
  • 当我尝试在下一个 jsp 中读取保存的参数时,我得到的是“null”而不是选定的值。我不知道我是否提交了表单,但我通过以下方式进入下一个 jsp:

    下一个 →

    我应该插入一种提交声明?感谢您的帮助!

标签: javascript jsp drop-down-menu selectedvalue


【解决方案1】:

一个可能的问题是您的选择菜单名称为 country,但 ID 不是 country。因此,您不会使用 document.getElementById("country"); 获得选择菜单

您可以通过在 &lt;select&gt; 标签中添加 id 来解决此问题:

<select id="country" name="country" size="6">

但是,您不需要 javascript 将选定的值发送到服务器。

您应该在表单中添加一个提交按钮:

<input type="submit" />

别忘了在&lt;form&gt; 标签中配置action:

<form name="ListForm" action="[server url]"> 

【讨论】:

  • 确实如此,谢谢。但它并没有解决问题。不过,我得到的是“null”而不是选定的值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-22
  • 2021-09-01
  • 2019-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多