使用ajax实现Dom节点表单的增删改查

前端部分

html部分

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="showstu.css">

</head>

<body onload="ajax5()">
<h1 class="title">学生数据展示</h1>
<div id="box">
  <div class="form">

    <form action="" class="update">
      姓名<input type="text" class="xm1" placeholder="请输入更新姓名"><br>
      性别<input type="radio" class="xb1" value="男" name="sex" checked>男
      <input type="radio" value="男" class="xb1" name="sex">女<br>
      年龄<input type="text" placeholder="请输入年龄" class="nl1"><br>
      电话<input type="text" class="dh1"><br>
      成绩<input type="text" class="cj1"><br>
      学校<input type="text" class="xx1"><br>
      <input type="button" id="sub1" value="更新">
    </form>



    <form action="" class="add">
      姓名<input type="text" class="xm" placeholder="请输入姓名"><br>
      性别<input type="radio" class="xb" value="男" name="sex" checked>男
      <input type="radio" value="男" class="xb" name="sex">女<br>
      年龄<input type="text" placeholder="请输入年龄" class="nl"><br>
      电话<input type="text" class="dh"><br>
      成绩<input type="text" class="cj"><br>
      学校<input type="text" class="xx"><br>
      <input type="button" id="sub" value="添加">
    </form>
  </div>
  <div class="show">
    <table class="table">
      <thead>
      <tr class="tr">
        <th class="th">ID</th>
        <th>姓名</th>
        <th>性别</th>
        <th>年龄</th>
        <th>电话</th>
        <th>成绩</th>
        <th>学校</th>
        <th>操作1</th>
        <th>操作2</th>
      </tr>
      </thead>
      <tbody id="tab">
      </tbody>
    </table>
  </div>
</div>

</body>

css部分

*{
    margin:0;
    padding:0;
}
body{
    background-color: #e6e6fa;
    color: #03515d;
    text-decoration: none;
}
.table{
    border: 1px dashed #E8CCFF;
    width:900px;
    height: 305px;
    font-size: 18px;
    border-collapse: collapse;
    text-align: center;
    float: right;
    font-family: STZhongsong;
    line-height: 35px;
}
.table td:hover {
    background-color: #FFDEAD;
}
table th:nth-child(even) {
    background-color: #D1BBFF;
}

table th:nth-child(odd) {
    background-color: #E8CCFF;
}
.tr{
    border-collapse: collapse;
    height: 20px;
    border: 2px dashed #E8CCFF;
    text-align: center;
    font-size: 19px;
}
.th,td{
    word-wrap: break-word;
    max-width: 300px;
    text-align: center;
    vertical-align: middle;
    border: 2px dashed #E8CCFF;
}
#box{
    width: 1300px;
    margin:30px auto;
}
.form{
    float:left;
    margin-left: 20px;
    font-family: STZhongsong;
}
.form input{
    margin:10px;
}
.update{
    background-color: #d6cef6;
    margin-bottom: 10px;
}
.add{
    background-color: #d6cef6;
}
.show{
    float: right;
    background-color: #d9e4f5;
}
button{
    font-size: 17px;
    font-family: STZhongsong;
    border: none;
    background-color: #d6cef6;

}
.title{
    text-align: center;
    margin:20px;
    font-size: 40px;
    font-family: STZhongsong;
    background-color: #d6cef6;
}

js部分

<script>
  let data;
  ajax5();
  function ajax5() {
    //1.创建ajax1对象
    let xmlHttpRequest = new XMLHttpRequest();

    xmlHttpRequest.open("get","/servletstudy_war_exploded/ajax5",true);

    xmlHttpRequest.onreadystatechange=function (){

      if (xmlHttpRequest.readyState == 4){
        if (xmlHttpRequest.status==200){

          data = JSON.parse(xmlHttpRequest.responseText);
          //把json格式的字符串转换成json格式的对象 序列化
          tab.innerHTML = "";
          init();
        }
      }
    }
    xmlHttpRequest.send();
  }
  var pos;
  let tab = document.getElementById("tab");
  var update1 = document.querySelector(".update");
  var add1 = document.querySelector(".add");

  //1.渲染数据
  function init() {
//1.逐条遍历数据
    for (let index = 0; index < data.length;index++) {

//2.生成一行tr
      let tr = document.createElement("tr")

      if (index % 2 == 0) {
        tr.style.backgroundColor = "white";
      }

//3.生成行内的td
      for (let j = 0; j < Object.keys(data[0]).length + 2; j++) {
        let td = document.createElement("td")
        tr.appendChild(td);//添加到tr
      }
//4,给每一行的td赋初值
      const keysOrder = ['id', 'name', 'sex', 'age', 'tel', 'scores', 'school']; // 定义需要的顺序
      for (let i = 0; i < keysOrder.length; i++) {
        const key = keysOrder[i]; // 获取当前属性名
        tr.children[i].innerHTML = data[index][key] !== undefined ? data[index][key] : ''; // 确保值存在
      }

//5.创建操作按钮
      let button = document.createElement("button")
      let button1 = document.createElement("button")
      button.innerHTML = "删除";
      button1.innerHTML = "更新";
//2.删除数据
      button.onclick = del(index);
      button1.onclick =update(index);
//6.添加按钮对象
      tr.children[Object.keys(data[0]).length].appendChild(button)
      tr.children[Object.keys(data[0]).length+1].appendChild(button1)

      tab.appendChild(tr);
    }
  }

  //点击按钮实现,删除操作
  function del(index) {//想想,为啥这么写?好处是啥
    return function () {

      if (window.confirm("你确定要删除吗?")) {
        let sc={
          id:data[index].id
        }
        //字符串  对象--》后端  --》对象  序列化
        let s = encodeURIComponent(JSON.stringify(sc));
        //1.创建ajax1对象
        let xmlHttpRequest = new XMLHttpRequest();
//2.配置向后端请求类型get post 异步请求数据 传递数据 2 &
        xmlHttpRequest.open("get","/servletstudy_war_exploded/ajax7?id="+s,true);
//监听数据是否请求成功
        xmlHttpRequest.onreadystatechange=function (){
//服务和客户端握手
          if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status==200){
            if (xmlHttpRequest.responseText=="success"){
              alert("数据删除成功");
              tab.innerHTML = "";
              add1.reset();
              ajax5();
            }
          }
        }
        //4.发送请求
        xmlHttpRequest.send();
        // data.splice(index, 1);
        // tab.innerHTML = "";
        // init();
      }
    }

  }

  //点击按钮,实现数据回显效果
  function update(index){//想想,为啥这么写?好处是啥
    return function () {
      var update = document.querySelector(".update");
      var add = document.querySelector(".add");
// update.style.display = "none";
// add.style.display = "block";
// data[data.length-1].id+1;
      document.querySelector(".xm1").value = data[index].name
// document.querySelectorAll(".xb1")[0].checked?"男":"女";
      document.querySelector(".nl1").value = data[index].age;
      document.querySelector(".dh1").value = data[index].tel;
      document.querySelector(".cj1").value = data[index].scores
      document.querySelector(".xx1").value = data[index].school
      pos=index;//记录更新的数组下标
    }

  }


  //3.数据添加
  let sub = document.getElementById("sub")
  sub.onclick = function () {
    let id = data[data.length - 1].id + 1;
    let xm = document.querySelector(".xm").value
    let xb = document.querySelectorAll(".xb")[0].checked ? "男" : "女";
    let nl = document.querySelector(".nl").value
    let dh = document.querySelector(".dh").value
    let cj = document.querySelector(".cj").value
    let xx = document.querySelector(".xx").value
//数据入库
    let newobj = {
      "id": id,
      "name": xm,
      "sex": xb,
      "age": nl,
      "tel": dh,
      "scores": cj,
      "school": xx
    }

    //字符串  对象--》后端  --》对象  序列化
    let s = encodeURIComponent(JSON.stringify(newobj));
    //1.创建ajax1对象
    let xmlHttpRequest = new XMLHttpRequest();
//2.配置向后端请求类型get post 异步请求数据 传递数据 2 &
    xmlHttpRequest.open("get","/servletstudy_war_exploded/ajax6?data="+s,true);
//监听数据是否请求成功
    xmlHttpRequest.onreadystatechange=function (){
//服务和客户端握手
      if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status==200){
        if (xmlHttpRequest.responseText=="success"){
          alert("数据入库成功");
          tab.innerHTML = "";
          add1.reset();
          ajax5();
        }
      }
    }
    //4.发送请求
    xmlHttpRequest.send();
  }

  //4实现更新
  let sub1 = document.getElementById("sub1")
  sub1.onclick = function () {
    let id = data[pos].id;
    let xm = document.querySelector(".xm1").value
    let xb = document.querySelectorAll(".xb1")[0].checked ? "男" : "女";
    let nl = document.querySelector(".nl1").value
    let dh = document.querySelector(".dh1").value
    let cj = document.querySelector(".cj1").value
    let xx = document.querySelector(".xx1").value
//更新这条数据
    let pos1 = {
      "id": id,
      "name": xm,
      "sex": xb,
      "age": nl,
      "tel": dh,
      "scores": cj,
      "school": xx
    }
    //字符串  对象--》后端  --》对象  序列化
    let update = encodeURIComponent(JSON.stringify(pos1));
    //1.创建ajax1对象
    let xmlHttpRequest = new XMLHttpRequest();
//2.配置向后端请求类型get post 异步请求数据 传递数据 2 &
    xmlHttpRequest.open("get","/servletstudy_war_exploded/ajax8?upd="+update,true);
//监听数据是否请求成功
    xmlHttpRequest.onreadystatechange=function (){
//服务和客户端握手
      if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status==200){
        if (xmlHttpRequest.responseText=="success"){
          alert("数据更新成功");
          tab.innerHTML = "";
          update1.reset();
          ajax5();
        }
      }
    }
    //4.发送请求
    xmlHttpRequest.send();
  }
</script>

Ajax部分

查找:

@WebServlet("/ajax5")
public class ajax5 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        resp.setContentType("application/json");
        req.setCharacterEncoding("utf-8");//响应用户请求时,告知用户服务器的编码
        List<Stu> stus = JdbcTools3.queryBeanList("select * from students", Stu.class);
        String res = JSON.toJSONString(stus);
        System.out.println("后端json格式的字符串 = " + res);

        PrintWriter writer = resp.getWriter();
        writer.write(res);
        writer.flush();
        writer.close();
    }
}

添加:

@WebServlet("/ajax6")
public class ajax6 extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        resp.setContentType("application/json");
        req.setCharacterEncoding("utf-8");//响应用户请求时,告知用户服务器的编码
        String data = req.getParameter("data");
        System.out.println("data = " + data);
        JSONObject jsonObject = JSONObject.parseObject(data.toString());
        Integer id = Integer.valueOf( jsonObject.getString("id"));
        String name = jsonObject.getString("name");
        String sex = jsonObject.getString("sex");
        Integer age = Integer.valueOf( jsonObject.getString("age"));
        String tel = jsonObject.getString("tel");
        String scores = jsonObject.getString("scores");
        String school = jsonObject.getString("school");
        Stu stu = new Stu();
        stu.setId(id);stu.setName(name);
        stu.setSex(sex);stu.setAge(age);stu.setTel(tel);
        stu.setScores(scores);stu.setSchool(school);
        try {
            int add = jdbcTools.add("insert into students values(?,?,?,?,?,?,?)", id,name,sex,age,tel,scores,school);
            System.out.println(add);
        } catch (Exception e) {
            e.printStackTrace();
        }
        PrintWriter writer = resp.getWriter();
        writer.write("success");
    }
}

删除:

@WebServlet("/ajax7")
public class ajax7 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        resp.setContentType("application/json");
        req.setCharacterEncoding("utf-8");//响应用户请求时,告知用户服务器的编码
        String id= req.getParameter("id");
        System.out.println("id = " + id);
        JSONObject jsonObject = JSONObject.parseObject(id.toString());
        Integer id1 = Integer.valueOf( jsonObject.getString("id"));
        int delete = 0;
        try {
            delete = jdbcTools.delete("delete from students where id = ?", id1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("delete = " + delete);
        PrintWriter writer = resp.getWriter();
        writer.write("success");
    }
}

更新:

@WebServlet("/ajax8")
public class ajax8 extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        resp.setContentType("application/json");
        req.setCharacterEncoding("utf-8");//响应用户请求时,告知用户服务器的编码
        String upd = req.getParameter("upd");
        System.out.println("upd = " + upd);
        JSONObject jsonObject = JSONObject.parseObject(upd.toString());
        Integer id = Integer.valueOf( jsonObject.getString("id"));
        System.out.println("id = " + id);
        String name = jsonObject.getString("name");
        String sex = jsonObject.getString("sex");
        System.out.println("sex = " + sex);
        Integer age = Integer.valueOf( jsonObject.getString("age"));
        String tel = jsonObject.getString("tel");
        String scores = jsonObject.getString("scores");
        String school = jsonObject.getString("school");
        Stu stu = new Stu();
        stu.setId(id);stu.setName(name);
        stu.setSex(sex);stu.setAge(age);stu.setTel(tel);
        stu.setScores(scores);stu.setSchool(school);
        System.out.println("sex = " + sex);
        System.out.println("stu = " + stu);
        try {
            int update1 = JdbcTools3.update1("update students set name=?,sex=?,age=?,tel=?,scores=?,school=? where id=?",name,sex,age,tel,scores,school,id);
            System.out.println("update1 = " + update1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        PrintWriter writer = resp.getWriter();
        writer.write("success");
    }
}

  • 12
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值