我有这张桌子:
<table style="width:100%">
<table id="Dest_table">
<tr>
<th>Check </th>
<th>Country</th>
<th>City</th>
<th>Url of Destination</th>
<th>Category</th>
</tr>
<tr> <%while(rs.next()){ %>
<td><INPUT type="checkbox" name="chk"/></td>
<td> <%=rs.getString("COUNTRY") %></td>
<td> <%=rs.getString("CITY") %> </td>
<td> <a href=<%=rs.getString("URL") %> > <%=rs.getString("URL") %> </a>
</td>
</tr>
<% } %>
</table>
这个函数删除表上的一行:
<SCRIPT language="javascript">
function deleteRow(Dest_table) {
try {
var table = document.getElementById(Dest_table);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
}
</SCRIPT>
但超出我在函数中删除的行,我需要在数据库中删除它的同一行,但我不知道如何...任何帮助?
答案 0 :(得分:1)
你可以尝试这个:
在表格中添加隐藏的输入。然后将数据库记录的行ID放在其上。
<tr> <%while(rs.next()){ %>
<td><input type="hidden" value="row_id" id="rows"/></td>
<!--insert your code here-->
</td>
创建一个删除数据库中的行的函数:
function delete(row_id) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST", jsp_url?row_id, false);
xmlhttp.send(null);
document.getElementById("table_id").innerHTML = xmlhttp.responseText;
}
其中 jsp_url 是您的jsp的url, row_id 是您要删除的表行的ID。然后调用循环中的delete函数删除表格行。
for(var i=0; i<rowCount; i++) {
<!--insert your code here-->
var row_id = document.getElementById('rows'+i).value;
if(null != chkbox && true == chkbox.checked) {
<!--insert your code here-->
delete(row_id);
}
}
答案 1 :(得分:0)
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
int id = Integer.parseInt(request.getParameter("id"));
StudentDAO db = new StudentDAO();
db.delete(id);
response.sendRedirect("list");
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
public void delete(int id) {
String sql = "DELETE FROM [dbo].[Student]\n"
+ " WHERE id = " + id;
try {
PreparedStatement statement = connection.prepareStatement(sql);
ResultSet rs = statement.executeQuery();
} catch (SQLException ex) {
Logger.getLogger(StudentDAO.class.getName()).log(Level.SEVERE, null, ex);
}
}