jQuery ajax()使用serialize()提交form数据到后台

1、选中要删除的学生信息

2、点击 删除选中 按钮,把复选框中的值取出提交到后台

3、后台获取选中的id

 

 4、前端也跟着删除数据

示例代码:

前端代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>学生信息列表</h1>
<input type="button" id="del" value="删除选中">
//表格外面加一个form表单包括table,为了序列化表单
//里面不需要添加method..就给一个id就行了 <form id="f"> <table border="1" id="tab"> <tr> <th>编号</th> <th>姓名</th> <th>性别</th> <th>年龄</th> <th>班级</th> <th>全选<input type="checkbox" id="selects"></th> </tr> </table> </form> </body> <script src="js/jquery-1.12.4.js"></script> <script> //页面加载时初始化数据(数据库读取数据) $(function () { $.ajax("stu",{ type:"post", success:function (data) { //后台响应回来 json 格式的数据 //循环遍历学生信息列表 $.each(data,function (index,obj) { $("#tab").append( "<tr>"+ "<td>"+obj.sid+"</td>"+ "<td>"+obj.sname+"</td>"+ "<td>"+obj.ssex+"</td>"+ "<td>"+obj.sage+"</td>"+ "<td>"+obj.clazz.cname+"</td>"+ // 注意!!! 在input里面需要 添加name,为了后台读取选中的值 req.getParameterValues("stuId"); "<td class='box'><input type='checkbox' name='stuId' value='"+obj.sid+"'></td>"+ "</tr>" ); }); //全选/全不选 var i=0; $("#selects").on("click",function () { if(i==0){ $("#tab :checkbox").prop("checked",true); i=1; }else{ $("#tab :checkbox").prop("checked",false); i=0; } }) //删除 $('#del').on("click",function () { //取出表单序列化的值 var param=$('#f').serialize(); //用ajax提交序列化的值 $.get("dels",param,function (data) { if(data==200){ //如果在后台返回来200数字表示后台在数据库已经删除成功 //后台删除成功之后前端用jQuery也随之删除对应的节点,为了不用重新再查询一遍数据 $(".box :checked").parent().parent().remove(); }else{ alert("删除失败!"); } }) /* * 也可以这种方式提交 * $.ajax("dels",{ type: 'get', data: $("#f").serialize(), success: function(data) { // your code ... } }); * */ }); } }); }) </script> </html>

后台代码:(只附上删除的Servlet代码)

@WebServlet("/dels")
public class DeleteServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //取出提交过来表单选中序列化的值 name都为stuId的
        //取出来是一个String[]数组
        String[] sids=req.getParameterValues("stuId");
        for (String str:sids) {
            System.out.println("获取id"+str);
        }
        //实例化dao方法
        StudentDao dao =new StudentDao();
        //调用删除的方法 返回int[]数组
        int[] row=dao.studelete(sids);
        //只需判断有没有数据即可,有就响应200表示成功后台删除成功,否则500删除失败
        resp.getWriter().println(row!=null?200:500);
    }
}

 

posted @ 2018-08-08 20:31  黄浩#  阅读(3304)  评论(0编辑  收藏  举报