-1

我对 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); 
%>

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

4

1 回答 1

0

一个可能的问题是您的选择菜单有名称country但没有 id country。因此你不会得到选择菜单document.getElementById("country");

您可以通过在<select>标签中添加 id 来解决此问题:

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

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

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

<input type="submit" />

并且不要忘记action在您的<form>标签中配置:

<form name="ListForm" action="[server url]"> 
于 2013-01-13T13:20:57.313 回答