This question already has answers here:
Call Servlet and invoke Java code from JavaScript along with parameters
                                
                                    (3个答案)
                                
                        
                3年前关闭。
            
        

我有复选框的值,单击删除值后,该类型必须发送到名为DeleteServlet的servlet。请帮我如何发送值?

<html>
    <head>
    <script type="text/javascript">
     function get_check_value(chkbox){
           if(chkbox.checked){
          var Values=chkbox.value;
          //send this Values to servlet

             }

    }
    function doDelete(theClick){
    var type=theClick;
//send this type to servlet
    alert(type);

    }

    </script>
    </head>
    <%String user=request.getParameter("Users"); %>
    <body>
    <%

    String User[]=user.trim().split(" ");

    for(int i=0;i<User.length;i++){%>
     <center>
        <form name='list' action='AddUserServlet'>

     <%  out.println("<input type='checkbox' name='user" + i + "' value='"+ User[i] + "' onClick='return get_check_value(this)'>" + User[i]+ "</input>" ); %>

    </form>

    <%}%>

        <input type="submit" value="ADD" name="b1" >
        <input type="submit" value="MODIFY" name="b1">
     <input type="submit" value="DELETE" name="b1" onClick="return doDelete(value)" >

      </center>

    </body>
    </html>


我在警报框中尝试了此“ document.list.user.value”作为未定义对象。要发送到servlet,我尝试了以下代码,但未读取

chk_val=chkbox.value;
document.add.action = "AddUserServlet?type=delete&name="+chk_val;
 document.add.submit();

最佳答案

您根本不需要Javascript。

只需更改您的代码,即可生成HTML表单,如下所示:

<form action="AddUserServlet" method="post">
    <input type="checkbox" name="user" value="1">
    <input type="checkbox" name="user" value="2">
    <input type="checkbox" name="user" value="3">
    <input type="checkbox" name="user" value="4">
    <input type="checkbox" name="user" value="5">

    <input type="submit" name="b1" value="ADD">
    <input type="submit" name="b1" value="MODIFY">
    <input type="submit" name="b1" value="DELETE">
</form>


(复选框值必须是唯一的用户ID)

然后在request.getParameterValues()中使用AddUserServlet

String b1 = request.getParameter("b1");
if ("DELETE".equals(b1)) {
    String[] users = request.getParameterValues("user");
    // ...
}


users数组将包含检查的值(1、2、3、4和/或5)。

09-09 21:56