21 July 2016

Web Service Java Spring Delete to Database - Ajax json - jquery P3


P1: Select
P2: Insert
Tiếp tục >> phần này ta triển khai thêm chức năng Delete
Class DemoService
Java 2016
//delete User RequestBody
@RequestMapping(value="/deleteUser",method = RequestMethod.POST)
 public void  deleteStudentRB(@RequestBody String userId) {
   UserDAO userDAO = new UserDAO();
   userDAO.delStudent(userId);
 }
}
Class UserDAO
Java 2016
public void delStudent(String id){
 try {
  stmt  = conn.prepareStatement("DELETE FROM student.student WHERE id=?");
  stmt.setString(1, id);
  
  stmt.executeUpdate();
 } catch (SQLException e) {
  e.printStackTrace();
 }
}



index.html
Java 2016
<!doctype html>
<html class="no-js" lang="">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title>Demo Hello WebService</title>  
</head>
<body>  
        <script>
  window.jQuery || document.write('<script src="jquery-1.12.0.min.js"><\/script>')
  </script>
        <script>
  (function($){
    $(document).ready(function() {
     selectUser();
     insertUser();
     deleteUser();
    });
    function selectUser(){
     $.get("http://localhost:8080/viewAllUser", function(data){
      $.each(data, function(key, value){
       $(".Student").append("<p> Name: " + value.name + " </br> Age: " + value.age + "</p>");
      });
     });
    }
    
    function insertUser(){
    $("#save").click(function(){
     var name = $("#name").val();
     var age = $("#age").val();

     var data = JSON.stringify({
      "name": name,
      "age": age,
     });

     $.ajax({
      type: "POST",
      url: "http://localhost:8080/addUser",
      data: data,
      dataType: 'appLication/json',
      contentType: 'appLication/json',
      complete: function(){
       $("#name").val("");
       $("#age").val("");
       location.reload();
      }
     });
    });
    }

    function deleteUser(){
    $("#delSubmit").click(function(){
     var id = $("#id").val();

     $.ajax({
      type: "POST",
      url: "http://localhost:8080/deleteUser",
      data: id,
      dataType: "text",
      contentType: 'appLication/json',
      complete: function(){
       
      }
     
     });
    });
    }
    
   })(jQuery);
  </script>
        <div class="Student"> 
            <div class="name"></div>
            <div class="age"></div>
        </div> 
   <div id="form-user">Insert: 
                <input id="name" type="text" name="name" placeholder="Name">
                <input id="age" type="number" name="age" placeholder="Age">
                <button id="save" type="submit">Insert</button>
        </div>
  <div id="deleteUser">Delete:
                <input id="id" type="text" name="id" placeholder="Id">
                <button id="delSubmit" type="submit">Delete</button>
        </div>
</body>
</html>

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang