當(dāng)前位置:首頁 >  站長 >  編程技術(shù) >  正文

AJAX實(shí)現(xiàn)數(shù)據(jù)的增刪改查操作詳解java后臺

 2020-11-03 13:52  來源: 腳本之家   我來投稿 撤稿糾錯

  域名預(yù)訂/競價(jià),好“米”不錯過

這篇文章主要介紹了AJAX實(shí)現(xiàn)數(shù)據(jù)的增刪改查操作,結(jié)合實(shí)例形式詳細(xì)分析了ajax結(jié)合java后臺實(shí)現(xiàn)數(shù)據(jù)庫增刪改查相關(guān)操作技巧,需要的朋友可以參考下

本文實(shí)例講述了AJAX實(shí)現(xiàn)數(shù)據(jù)的增刪改查操作。分享給大家供大家參考,具體如下:

主頁:index.html

<!DOCTYPE html>
<html>
 <head>
 <meta charset="UTF-8">
 <title></title>
 <script src=">
 </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 += '<tr><td></td><td></td><td></td><td></td><td></td><td></td></tr>';
 }
 $("#queryResult").html(x);*/
 function submit() {
 var pno = $("#pno").val();
 var name = $("#name").val();
 var sex = $('input[name="sex"]:checked').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 = $('input[name="sex_up"]:checked').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('";
 sqlInsert += pno +"','";
 sqlInsert += name +"','";
 sqlInsert += sex +"',";
 sqlInsert += age +",";
 sqlInsert += height +",";
 sqlInsert += weight +")";
 
 int message = MysqlUtil.add(sqlInsert);
 String rep = "";
 if(message == 1) {
  rep = "{\"code\":200,\"message\":\"成功插入數(shù)據(jù)庫\"}";
 }else {
  rep = "{\"code\":\"999\",\"message\":\"插入失敗了\"}";
 }
 response.getWriter().write(rep);
 
 
 }
 
}

刪除的Servlet: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);
 }
 
}

更新的Servlet: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='"+ pno +"',";
 sqlupdate += "Pname='"+ name +"',";
 sqlupdate += "Psex='"+ sex +"',";
 sqlupdate += "Page="+ age +",";
 sqlupdate += "Pheight="+ height +",";
 sqlupdate += "Pweight="+ weight;
 sqlupdate += " where Pno='"+pno+"'";
 System.out.println(sqlupdate);
 int message = MysqlUtil.update(sqlupdate);
 String rep = "";
 if(message == 1) {
  rep = "{\"code\":\"200\",\"message\":\"成功插入數(shù)據(jù)庫\"}";
 }else {
  rep = "{\"code\":\"999\",\"message\":\"插入失敗了\"}";
 }
 response.getWriter().write(rep);
 
 }
 
}

查詢的Servlet: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);
 }
 
 
 
}

頁面如下:

對應(yīng)的數(shù)據(jù)庫:

 

git克隆地址:https://github.com/dreamiboy/JDBCUtil.git

更多關(guān)于ajax相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《jquery中Ajax用法總結(jié)》、《JavaScript中ajax操作技巧總結(jié)》、《PHP+ajax技巧與應(yīng)用小結(jié)》及《asp.net ajax技巧總結(jié)專題》

希望本文所述對大家ajax程序設(shè)計(jì)有所幫助。

來源:腳本之家

鏈接:https://www.jb51.net/article/187854.htm

申請創(chuàng)業(yè)報(bào)道,分享創(chuàng)業(yè)好點(diǎn)子。點(diǎn)擊此處,共同探討創(chuàng)業(yè)新機(jī)遇!

相關(guān)標(biāo)簽
ajax
java

相關(guān)文章

  • 參加Java培訓(xùn)班有用嗎?這個問題大家要怎么看待

    在眾多的編程培訓(xùn)中,Java軟件開發(fā)作為老牌兒的編程主流,從發(fā)展前景上看,無論是現(xiàn)在還是將來,依然會持續(xù)火爆的狀態(tài)。對于當(dāng)下年輕人想要快速的掌握這項(xiàng)技術(shù),進(jìn)入到這個行業(yè),最為熱議的話題是“參加Java培訓(xùn)班有用嗎”。小編可以肯定的回答,是有用的,學(xué)習(xí)的根據(jù)來自于興趣,如果大家是真的熱愛這行,在加上專

    標(biāo)簽:
    java
  • 動力節(jié)點(diǎn)南京Java培訓(xùn)口碑教學(xué),滿分教學(xué)就業(yè)體驗(yàn)

    江南佳地,邂逅金陵,動力節(jié)點(diǎn)南京Java培訓(xùn)校區(qū),為長三角地帶的發(fā)展注入專業(yè)Java教培力量,動力節(jié)點(diǎn)自09年成立至今,專注Java培訓(xùn)教學(xué),一直秉承著“為學(xué)員服務(wù)”的唯一教育理念,堅(jiān)持口碑教學(xué),被業(yè)界稱為“口口相傳的Java培訓(xùn)黃埔軍校”。

    標(biāo)簽:
    java
    java培訓(xùn)
  • 動力節(jié)點(diǎn)廣州Java培訓(xùn),為大家撐起一個IT的未來

    廣州動力節(jié)點(diǎn)Java培訓(xùn)機(jī)構(gòu),一直以來專注Java的教學(xué),深耕教育,穩(wěn)扎穩(wěn)打,在行業(yè)具有“口口相傳的黃埔軍?!敝Q,有句話說的好“沒有量變的積累,哪來質(zhì)變的飛躍”動力節(jié)點(diǎn)和你一起,扎扎實(shí)實(shí)做教育,你們扎扎實(shí)實(shí)學(xué)本領(lǐng),時(shí)刻準(zhǔn)備著,有朝一日,風(fēng)自會來。

    標(biāo)簽:
    java
    在線培訓(xùn)
  • 動力節(jié)點(diǎn)成都Java培訓(xùn)招生源于口碑,業(yè)界巨頭

    為了能夠搭乘互聯(lián)網(wǎng)的快車,實(shí)現(xiàn)人生的逆轉(zhuǎn),不少年輕人選擇動力節(jié)點(diǎn)成都Java培訓(xùn),動力節(jié)點(diǎn)作為Java職業(yè)培訓(xùn),沒有理由不去擔(dān)起這份沉甸甸的信任,所以,自09年創(chuàng)立起,一直專注于Java的教學(xué),將全部的資源

  • 參加動力節(jié)點(diǎn)北京Java培訓(xùn)會讓學(xué)者更加有信心

    通過Java培訓(xùn)出來的同學(xué)與沒參加過培訓(xùn)的同學(xué)差距還是有不少的,同學(xué)一直以來對參加培訓(xùn)都保持著猶豫的心態(tài),其實(shí)大家了解后會發(fā)現(xiàn),不管是對零基礎(chǔ)還是有編程認(rèn)知的同學(xué)來講,參與更加密集、系統(tǒng)化的培訓(xùn)

熱門排行

信息推薦