读取选择框的选定值并将其传递给jsp



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

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

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

你可以通过添加一个id到你的<select>标签来修复这个问题:

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

但是你不需要javascript来发送选择的值给服务器。

你应该给你的表单添加一个提交按钮:

<input type="submit" />

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

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

最新更新