AJAX는 데이터 추가, 삭제, 수정 및 쿼리 작업을 구현합니다.

coldplay.xixi
풀어 주다: 2020-08-27 16:26:50
앞으로
4290명이 탐색했습니다.

AJAX는 데이터 추가, 삭제, 수정 및 쿼리 작업을 구현합니다.

【추천 관련 기사: ajax 비디오 튜토리얼

이 기사의 예에서는 데이터 추가, 삭제, 수정 및 쿼리 작업의 AJAX 구현을 설명합니다. 참조를 위해 모든 사람과 공유하세요. 세부 사항은 다음과 같습니다.

홈페이지: index.html

<!DOCTYPE html>
<html>
 <head>
 <meta charset="UTF-8">
 <title></title>
 <script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
 </head>
 <body>
 编号:<input type="text" value="" id="pno"/><br>
 姓名:<input type="text" value="" id="name"/><br>
 性别:男:<input type="radio" name="sex" value="男">女:<input type="radio" name="sex" value="女"><br>
 年龄:<select id="age">
  <option value="15">15</option>
  <option value="16">16</option>
  <option value="17">17</option>
  <option value="18">18</option>
  <option value="19">19</option>
  <option value="20">20</option>
  <option value="21">21</option>
  <option value="22">22</option>
  <option value="23">23</option>
  <option value="24">24</option>
  <option value="25">25</option>
 </select><br>
 身高:<input type="text" value="" id="height"/><br>
 体重:<input type="text" value="" id="weight"/><br>
 <input type="button" value="插入" id="btn_1" onclick="submit()"/>
 <br>
 <br>
 <br>
 
 编号:<input type="text" value="" id="pno_query"/>
 <input type="button" value="查询" id="btn_2" onclick="query()"/>
 <table id="queryResult">
  <tr>
  <td>编号</td>
  <td>姓名</td>
  <td>性别</td>
  <td>年龄</td>
  <td>身高</td>
  <td>体重</td>
  </tr>
  <tr>
  <td></td>
  <td></td>
  <td></td>
  <td></td>
  <td></td>
  <td></td>
  </tr>
 </table>
 
 
 <br>
 <br>
 <br>
 编号:<input type="text" value="" id="pno_del"/>
 <input type="button" value="删除" id="btn_3" onclick="del()"/>
 
 <br>
 <br>
 <br>
 编号:<input type="text" value="" id="pno_up"/><br>
 姓名:<input type="text" value="" id="name_up"/><br>
 性别:男:<input type="radio" name="sex_up" value="男">女:<input type="radio" name="sex_up" value="女"><br>
 年龄:<select id="age_up">
  <option value="15">15</option>
  <option value="16">16</option>
  <option value="17">17</option>
  <option value="18">18</option>
  <option value="19">19</option>
  <option value="20">20</option>
  <option value="21">21</option>
  <option value="22">22</option>
  <option value="23">23</option>
  <option value="24">24</option>
  <option value="25">25</option>
 </select><br>
 身高:<input type="text" value="" id="height_up"/><br>
 体重:<input type="text" value="" id="weight_up"/><br>
 <input type="button" value="更新" id="btn_4" onclick="update()"/>
 
 </body>
 
 <script type="text/javascript">
 /*
 var x = $("#queryResult").html();
 
 for(var i=0; i < 20 ; i++) {
  x += &#39;<tr><td></td><td></td><td></td><td></td><td></td><td></td></tr>&#39;;
 }
 $("#queryResult").html(x);*/
 function submit() {
 var pno = $("#pno").val();
 var name = $("#name").val();
 var sex = $(&#39;input[name="sex"]:checked&#39;).val();
 var age = $("#age").val();
 var height = $("#height").val();
 var weight = $("#weight").val();
 
 var data={
  
  "pno":pno,
  "name":name,
  "sex":sex,
  "age":age,
  "height":height,
  "weight" : weight
 }
 
 
 $.ajax({
  type : "post",
  url : "Hello",
  data : data,
  cache : true,
  async : true,
  success: function (data ,textStatus, jqXHR){
     if(data.code == 200){
      alert("插入成功了");
     }else{
      alert(data.message);
     }
   },
     error:function (XMLHttpRequest, textStatus, errorThrown) {   
      
       alert(typeof(errorThrown));
     }
  
 });
 }
 
 
 function query() {
 
 var pno = $("#pno_query").val(); 
 var str = ["编号","姓名","性别","年龄","身高","体重"];
 $.ajax({
  type : "post",
  url : "HelloQuery",
  data : {
  "pno": pno
  },
  cache : true,
  async : true,
  success: function (data ,textStatus, jqXHR){
  //data = $.parseJSON(data);
  var j = 0;
  var x = 1;
  //for(var i=1; i <20; i++) {
   for(var p in data){//遍历json对象的每个key/value对,p为key
   console.log(data[p]);
   if(j == 6) {
    j = 0;
    x++;
   }
    $("#queryResult tr:eq("+x+") td:eq("+j+")").html(data[p]);
    console.log(data[p]);
    j++;
   }
  //}
  
  
  
     
   },
     error:function (XMLHttpRequest, textStatus, errorThrown) {   
      
       alert(typeof(errorThrown));
     }
  
 });
 }
 
 function del() {
 var pno = $("#pno_del").val(); 
 
 $.ajax({
  type : "post",
  url : "HelloDelete",
  data : {
  "pno": pno
  },
  cache : true,
  async : true,
  success: function (data ,textStatus, jqXHR){
  if(data.code == 200){
      alert("删除成功了");
     }else{
      alert(data.message);
     }
   },
     error:function (XMLHttpRequest, textStatus, errorThrown) {   
      
       alert(typeof(errorThrown));
     }
  
 });
 }
 
 function update() {
 var pno = $("#pno_up").val();
 var name = $("#name_up").val();
 var sex = $(&#39;input[name="sex_up"]:checked&#39;).val();
 var age = $("#age_up").val();
 var height = $("#height_up").val();
 var weight = $("#weight_up").val();
 
 var data={
  
  "pno":pno,
  "name":name,
  "sex":sex,
  "age":age,
  "height":height,
  "weight" : weight
 }
 
 
 $.ajax({
  type : "post",
  url : "HelloUpdate",
  data : data,
  cache : true,
  async : true,
  success: function (data ,textStatus, jqXHR){
     if(data.code == 200){
      alert("更新成功了");
     }else{
      alert(data.message);
     }
   },
     error:function (XMLHttpRequest, textStatus, errorThrown) {   
      
       alert(typeof(errorThrown));
     }
  
 });
 }
 
 
 
 </script>
</html>
로그인 후 복사

추가된 Serlvet: Hello.java

package com.web;
 
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.mysql.MysqlUtil;
 
/**
 * Servlet implementation class Hello
 */
@WebServlet("/Hello")
public class Hello extends HttpServlet {
 private static final long serialVersionUID = 1L;
    
  /**
   * @see HttpServlet#HttpServlet()
   */
  public Hello() {
    super();
    // TODO Auto-generated constructor stub
  }
 
 /**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 // TODO Auto-generated method stub
 response.getWriter().append("Served at: ").append(request.getContextPath());
 }
 
 /**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
 response.setCharacterEncoding("utf-8");
 response.setContentType("application/json; charset=utf-8");
 
 String pno = request.getParameter("pno");
 String name = request.getParameter("name");
 String sex = request.getParameter("sex");
 String age = request.getParameter("age");
 String height = request.getParameter("height");
 String weight = request.getParameter("weight");
 
 String sqlInsert = "INSERT INTO Person (Pno,Pname,Psex,Page,Pheight,Pweight) VALUES(&#39;";
 sqlInsert += pno +"&#39;,&#39;";
 sqlInsert += name +"&#39;,&#39;";
 sqlInsert += sex +"&#39;,";
 sqlInsert += age +",";
 sqlInsert += height +",";
 sqlInsert += weight +")";
 
 int message = MysqlUtil.add(sqlInsert);
 String rep = "";
 if(message == 1) {
  rep = "{\"code\":200,\"message\":\"成功插入数据库\"}";
 }else {
  rep = "{\"code\":\"999\",\"message\":\"插入失败了\"}";
 }
 response.getWriter().write(rep);
 
 
 }
 
}
로그인 후 복사

삭제된 서블릿: HelloDelete.java

package com.web;
 
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.mysql.MysqlUtil;
 
/**
 * Servlet implementation class HelloDelete
 */
@WebServlet("/HelloDelete")
public class HelloDelete extends HttpServlet {
 private static final long serialVersionUID = 1L;
    
  /**
   * @see HttpServlet#HttpServlet()
   */
  public HelloDelete() {
    super();
    // TODO Auto-generated constructor stub
  }
 
 /**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 // TODO Auto-generated method stub
 response.getWriter().append("Served at: ").append(request.getContextPath());
 }
 
 /**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 response.setCharacterEncoding("utf-8");
 response.setContentType("application/json; charset=utf-8");
 
 String pno = request.getParameter("pno");
 
 
 String sqlDel = "delete from Person where pno="+pno;
 
 
 int message = MysqlUtil.del(sqlDel);
 String rep = "";
 if(message == 1) {
  rep = "{\"code\":\"200\",\"message\":\"成功删除\"}";
 }else {
  rep = "{\"code\":\"999\",\"message\":\"删除失败\"}";
 }
 response.getWriter().write(rep);
 }
 
}
로그인 후 복사

업데이트된 서블릿: HelloUpdate.java

package com.web;
 
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.mysql.MysqlUtil;
 
/**
 * Servlet implementation class HelloUpdate
 */
@WebServlet("/HelloUpdate")
public class HelloUpdate extends HttpServlet {
 private static final long serialVersionUID = 1L;
    
  /**
   * @see HttpServlet#HttpServlet()
   */
  public HelloUpdate() {
    super();
    // TODO Auto-generated constructor stub
  }
 
 /**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 // TODO Auto-generated method stub
 response.getWriter().append("Served at: ").append(request.getContextPath());
 }
 
 /**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 response.setCharacterEncoding("utf-8");
 response.setContentType("application/json; charset=utf-8");
 
 String pno = request.getParameter("pno");
 String name = request.getParameter("name");
 String sex = request.getParameter("sex");
 String age = request.getParameter("age");
 String height = request.getParameter("height");
 String weight = request.getParameter("weight");
 
 String sqlupdate = "update Person set ";
// sqlupdate += "Pno=&#39;"+ pno +"&#39;,";
 sqlupdate += "Pname=&#39;"+ name +"&#39;,";
 sqlupdate += "Psex=&#39;"+ sex +"&#39;,";
 sqlupdate += "Page="+ age +",";
 sqlupdate += "Pheight="+ height +",";
 sqlupdate += "Pweight="+ weight;
 sqlupdate += " where Pno=&#39;"+pno+"&#39;";
 System.out.println(sqlupdate);
 int message = MysqlUtil.update(sqlupdate);
 String rep = "";
 if(message == 1) {
  rep = "{\"code\":\"200\",\"message\":\"成功插入数据库\"}";
 }else {
  rep = "{\"code\":\"999\",\"message\":\"插入失败了\"}";
 }
 response.getWriter().write(rep);
 
 }
 
}
로그인 후 복사

쿼리한 서블릿: HelloQuery.java

package com.web;
 
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.mysql.MysqlUtil;
 
/**
 * Servlet implementation class HelloQuery
 */
@WebServlet("/HelloQuery")
public class HelloQuery extends HttpServlet {
 private static final long serialVersionUID = 1L;
    
  /**
   * @see HttpServlet#HttpServlet()
   */
  public HelloQuery() {
    super();
    // TODO Auto-generated constructor stub
  }
 
 /**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 // TODO Auto-generated method stub
 response.getWriter().append("Served at: ").append(request.getContextPath());
 }
 
 /**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 response.setCharacterEncoding("utf-8");
 response.setContentType("application/json; charset=utf-8");
 String pno = request.getParameter("pno");
 String[] params = {"Pno","Pname","Psex","Page","Pheight","Pweight"};
 String sql = "select * from Person where Pno="+pno;
 String data = "{";
 
 String[] str = {"编号","姓名","性别","年龄","身高","体重"};
 List<Map<String,String>> listmap = new ArrayList<>();
 listmap = MysqlUtil.show(sql, params);
 for(int i =0 ; i<listmap.size();i++) {  
  for(int j=0 ; j<listmap.get(i).size();j++) {
  data += "\""+str[j]+"\":"+"\""+listmap.get(i).get(params[j])+"\",";  
  }
 }
 data = data.substring(0, data.length()-1);
 data += "}";
 
 
 System.out.println(data);
 response.getWriter().write(data);
 }
 
 
 
}
로그인 후 복사

페이지는 다음과 같습니다.

해당 데이터베이스:

관련 학습 권장 사항: 프로그래밍 동영상

위 내용은 AJAX는 데이터 추가, 삭제, 수정 및 쿼리 작업을 구현합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:jb51.net
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿