AJAX实现数据的增删改查操作详解【java后台】

本文实例讲述了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 += '<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\":\"成功插入数据库\"}";
 }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\":\"成功插入数据库\"}";
 }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);
 }
 
 
 
}

页面如下:

对应的数据库:

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

更多关于ajax相关内容感兴趣的读者可查看本站专题:《jquery中ajax用法总结》、《javascript中ajax操作技巧总结》、《php+ajax技巧与应用小结》及《asp.net ajax技巧总结专题

希望本文所述对大家ajax程序设计有所帮助。

相关文章