我的代码生成一个表,每行生成一个更新和删除按钮。当按下更新或删除按钮时,相对行的编号应该保存为会话变量,而是仅保存最后一行的编号。这个方法适用于PHP。我尝试通过html中的“onclick”属性分配会话变量,但它也不起作用。我理解为什么,并试图找到解决方法。
<%
while(result.next()){
%>
<tr>
<td><%out.print("<p>"+result.getInt(1)+"</p>"); %></td>
<td><%out.print("<p>"+result.getString(2)+"</p>"); %></td>
<td><%out.print("<p>"+result.getString(3)+"</p>"); %></td>
<td><%out.print("<p>"+result.getString(4)+"</p>"); %></td>
<td><%out.print("<p>"+result.getString(5)+"</p>"); %></td>
<td><%out.print("<p>"+result.getInt(6)+"</p>"); %></td>
<td>
<form action="DeleteUserServlet" method="POST">
<input type="submit" value="Delete"
onclick="<%session.setAttribute("id",result.getInt(1));%>">
</form>
<form action="UpdateUser.jsp" method="POST">
<input type="submit" value="Update" onclick="
<%session.setAttribute("id",result.getInt(1));%>">
</form>
</td>
</tr>
<%
}
%>
答案 0 :(得分:0)
Rather than trying to do this by setting the session variable you need to use a hidden input in the form.
<%
while(result.next())
{
%>
<tr>
<td><% out.print("<p>"+result.getInt(1)+"</p>"); %></td>
<td><% out.print("<p>"+result.getString(2)+"</p>"); %></td>
<td><% out.print("<p>"+result.getString(3)+"</p>"); %></td>
<td><% out.print("<p>"+result.getString(4)+"</p>"); %></td>
<td><% out.print("<p>"+result.getString(5)+"</p>"); %></td>
<td><% out.print("<p>"+result.getInt(6)+"</p>"); %></td>
<td>
<form action="DeleteUserServlet" method="POST">
<input type="hidden" name="id" value="<% out.print(result.getInt(1)); %>" />
<input type="submit" value="Delete" />
</form>
<form action="UpdateUser.jsp" method="POST">
<input type="hidden" name="id" value="<% out.print(result.getInt(1)); %>" />
<input type="submit" value="Update" />
</form>
</td>
</tr>
<%
}
%>
Why does what you were doing not work? All the Java code runs on the server-side, so even when you put something like <input type="submit" value="Update" onclick="<%session.setAttribute("id",result.getInt(1));%>">
that Java code setting the session attribute runs before the HTML page is sent to the browser, not when the user clicks that button. So what your code was actually doing was setting the session attribute over an over in a loop, and the resulting HTML going to the client was having the onClick value blank: <input type="submit" value="Update" onclick="">