Controller
//删除前的代码
@RequestMapping("/delete")
public String delUser(int id){
indexService.delUser(id);
return "redirect:index";
}
//删除更改后代码
@RequestMapping("/delete")
@ResponseBody
public String delUser(int id){
indexService.delUser(id);
return "1";
}
html
<!--修改前的代码-->
<tbody>
<tr th:each="user,key: ${msgList}">
<td th:text="${key.index+1}"></td>
<td th:text="${user.author}"></td>
<td th:text="${user.msg}"></td>
<td th:text="${user.vexp}"></td>
<td>
<a th:href="@{/toUpdate(id=${user.id})}">修改</a>
<a th:href="@{/delete(id=${user.id})}" onclick="return confirm('你整的要删除吗啊')">删除</a>
</td>
</tr>
</tbody>
<!--修改后代码-->
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<!--导入jq-->
<!--修改后代码-->
<tbody>
<tr th:each="user,key: ${msgList}" th:id="'id' + ${user.id}"><!--循环获取id-->
<td th:text="${key.index+1}"></td>
<td th:text="${user.author}"></td>
<td th:text="${user.msg}"></td>
<td th:text="${user.vexp}"></td>
<td>
<a th:href="@{/toUpdate(id=${user.id})}">修改</a>
<a th:onclick="'javascript:del('+${user.id}+');'">删除啊<!--调用下面js中定义的del()方法,id为参数--></a>
</td>
</tr>
</tbody>
<!--修改后代码-->
<script>
function del(id){ //定义del()方法
alert(id); //alert弹窗可以看到删除的属性id
$.post("/delete",{id:id},function (result){ //ajax,走post方法向/delete传值。传参数第一个id是形参,第二个id是传递过来的参数del(id)。第三个参数,function(result)回调函数。
if(result==1){ //走完/delete删除完事之后回调函数会返回controller中设置的return值1。
$("#id"+id).remove(); //id选择器锁定id,.remove()方法删除属性,不需要刷新
}
});
}
</script>