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程序设计有所帮助。

(0)

相关推荐

  • MVC+jQuery.Ajax异步实现增删改查和分页

    本文实例为大家分享了MVC+jQuery.Ajax异步实现增删改查和分页的具体代码,供大家参考,具体内容如下 1.Model层代码 using System; using System.Data; using System.Configuration; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; usin

  • AJAX+JAVA用户登陆注册验证的实现代码

    需求 通过ajax异步刷新页面验证用户输入的账号密码是否在数据库中存在. 技术栈 JSP+Servlet+Oracle 具体代码 JSP部分: <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transit

  • jQuery+datatables插件实现ajax加载数据与增删改查功能示例

    本文实例讲述了jQuery+datatables插件实现ajax加载数据与增删改查功能.分享给大家供大家参考,具体如下: 这里给大家分享一下我在项目中用datatables实现ajax加载数据与增删改查 注意,需要引入jquery.datatables.layer html代码: <div class="thead"> <input placeholder="请输入搜索内容" id="searchTitle" type=&quo

  • ajax java 实现自动完成功能

    百度建议给了我们极大的方便,就像我们跟人说话的时候,你点头他知尾,不用多费唇舌,这样我们与之相处久轻松愉悦. 都知道百度建议是用ajax做的,想要做的快速稳定,可复制可移植就不容易了.网上找了半天,好多都是asp或者php的,还有使用jquery的,但说明性文档太少,花时间研究还不如自己来写.根据一个pdf文档提供的资料,用了小半天时间,终于实现了.在此与大家分享. 原理流程图如下:  流程图很明白了,没什么要说的,以下帖代码. Javascript代码: 复制代码 代码如下: var xmlH

  • 在Java的Struts中判断是否调用AJAX及用拦截器对其优化

    Strut2判断是否是AJAX调用 1.   AJAX与传统Form表单 实际上,两者一般都是通过HTTP的POST请求.区别是浏览器提交Form表单后,期望服务器返回一个完整的HTML页面.而AJAX调用是由XMLHttpRequest对象(不同浏览器可能不一样)发出,浏览器期望服务器返回HTML片段即可,具体是JSON.XML等都没有要求.返回到浏览器后如何使用,也是由JS脚本自己决定的.   2. 请求是不是AJAX 那么对于服务器端,如何判断一个HTTP请求是不是AJAX调用?这需要看H

  • ajax提交到java后台之后处理数据的实现

    环境:eclipse+struts 要实现的效果:点击按钮提交数据到后台之后回到前台显示出来数据 index.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN&quo

  • jQuery的Ajax接收java返回数据方法

    1.前端Ajax请求如下: $.ajax({ type : "post", //async:false, url : PATH + "/product/selectPicture.action", dataType : "json", success : function(data) { $.each(data,function(k,v){ alert(k +":"+ v); }); } }); 2 其中PATH在jsp页面中

  • Javaweb使用cors完成跨域ajax数据交互

    跨域,指的是浏览器不能执行其他网站的脚本.它是由浏览器的同源策略造成的,是浏览器对JavaScript施加的安全限制. ajax本身实际上是通过XMLHttpRequest对象来进行数据的交互,而浏览器出于安全考虑,不允许js代码进行跨域操作,所以会警告. cors 全称:Cross-Origin Resource Sharing 中文意思:跨域资源共享 它在维基百科上的定义是:跨域资源共享(CORS )是一种网络浏览器的技术规范,它为Web服务器定义了一种方式,允许网页从不同的域访问其资源.而

  • 深入Ajax代理的Java Servlet的实现详解

    代码如下所示: 复制代码 代码如下: import java.io.IOException;import java.io.InputStream;import java.net.URL;import javax.servlet.ServletConfig;import javax.servlet.ServletException;import javax.servlet.ServletOutputStream;import javax.servlet.http.HttpServlet;impor

  • 详解Java Ajax jsonp 跨域请求

    1.什么是JSONP 一般来说位于 server1.example.com 的网页无法与不是 server1.example.com的服务器沟通,而 HTML 的<script> 元素是一个例外.利用 <script> 元素的这个开放策略,网页可以得到从其他来源动态产生的 JSON 资料,而这种使用模式就是所谓的 JSONP.用 JSONP 抓到的资料并不是 JSON,而是任意的JavaScript,用 JavaScript 直译器执行而不是用 JSON 解析器解析. JSONP是

  • Java使用Ajax实现跨域上传图片功能

    说明 : 图片服务器是用Nginx搭建的,用的是PHP语言 这个功能 需要 用到两个js文件: jquery.js和jQuery.form.js <script type="text/JavaScript" src="js/jquery.js"></script> <script type="text/javascript" src="js/jquery.form.js"></scri

随机推荐