移动App,AJAX异步请求,实现简单的增删改查

Posted YuW

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了移动App,AJAX异步请求,实现简单的增删改查相关的知识,希望对你有一定的参考价值。

用ajax发异步请求时,要注意url。“AppServer”为后台项目名,“LoginServlet.action”为web.xml中的<url-pattern></url-pattern>标签中的内容。

前台代码如下(核心代码):

index.html:

 1             $(function() {
 2                 $(\'#login\').click(function() {
 3                     var account = $("#account").val();
 4                     var passwords = $(\'#passwords\').val();
 5                     $.ajax({
 6                         url: "http://localhost:8080/AppServer/LoginServlet.action?ajaxType=jsonp",
 7                         dataType: "jsonp",
 8                         jsonpCallback: "jsonpCallback",
 9                         jsonp: "callback",
10                         data: {
11                             account: account,
12                             passwords: passwords,
13                         },
14                         success: function(server) {
15                             if (server.is) {
16                                 alert("登录成功");
17                                 $(location).attr(\'href\', \'main.html?account=\' + account);
18                             } else {
19                                 alert("登录失败:" + server.err);
20                             }
21                         },
22                         error: function(server) {
23                             alert("连接服务器失败");
24                         },
25                     });
26                 });
27                 $(\'#register\').click(function() {
28                     $(location).attr(\'href\', \'register.html\');
29                 });
30             })

register.html:

 1             $(function() {
 2                 $(\'#register\').click(function() {
 3                     var islen = ($(\'#password1\').val().length >= 6 && $(\'#password1\').val().length <= 12) && ($(\'#password2\').val().length >= 6 && $(\'#password2\').val().length <= 12);
 4                     var isID = $(\'#user_id\').val().length > 0 && $(\'#user_id\').val().length <= 18;
 5                     if (islen && isID) {
 6                         if ($(\'#password1\').val() == $(\'#password2\').val()) {
 7                             $.ajax({
 8                                 type: "post",
 9                                 url: "http://localhost:8080/AppServer/RegisterServlet.action?ajaxType=jsonp",
10                                 dataType: "jsonp",
11                                 jsonpCallback: "jsonpCallback",
12                                 jsonp: "callback",
13                                 data: {
14                                     account: $(\'#account\').val(),
15                                     passwords: $(\'#password1\').val(),
16                                     phone: $(\'#phone\').val(),
17                                     email: $(\'#email\').val(),
18                                     userId: $(\'#user_id\').val(),
19                                     userName: $(\'#user_name\').val(),
20                                     sex: $(\'input:radio:checked\').val(),
21                                 },
22                                 success: function(server) {
23                                     if (server.is) {
24                                         alert("注册成功");
25                                         $(location).attr(\'href\', \'index.html\');
26                                     } else {
27                                         alert("注册失败");
28                                     }
29                                 },
30                                 error: function(server) {
31                                     alert("连接服务器失败");
32                                 },
33                             });
34                         } else {
35                             alert(\'密码不一致!\');
36                         }
37                     } else {
38                         if (!isID) {
39                             alert(\'请输入正确的身份证!\');
40                         } else if (!islen) {
41                             alert(\'密码长度不一致\');
42                         } else {
43                             alert(\'请输入合法的信息!\');
44                         }
45                     }
46                 });
47             })

main.html:

  1             $(function() {
  2                 var loc = location.href;
  3                 var n1 = loc.length; //地址的总长度
  4                 var n2 = loc.indexOf("="); //取得=号的位置
  5                 var accounts = decodeURI(loc.substr(n2 + 1, n1 - n2));
  6                 $(\'#select\').click(function() {
  7                     $(\'#div2\').show(1500);
  8                     $(\'#div3\').hide(1500);
  9                     $.ajax({                
 10                         url: "http://localhost:8080/AppServer/MainServlet.action?ajaxType=jsonp&Type=select",
 11                         dataType: "jsonp",
 12                         jsonpCallback: "jsonpCallback",
 13                         jsonp: "callback",
 14                         data: {
 15                             account: accounts,
 16                         },
 17                         success: function(server) {
 18                             if (server.is) {
 19                                 $(\'#account\').val(server.account);
 20                                 $(\'#phone\').val(server.phone);
 21                                 $(\'#email\').val(server.email);
 22                                 $(\'#ids\').val(server.userId);
 23                                 $(\'#name\').val(server.userName);
 24                                 $(\'#password\').val(server.passwords);
 25                                 $(\'#sex\').val(server.sex);
 26                             } else {
 27                                 alert("查看失败!");
 28                             }
 29                         },
 30                         error: function(server) {
 31                             alert("连接服务器失败!");
 32                         },
 33                     });
 34                 });
 35                 $(\'#save\').click(function() {
 36                     var islen = $(\'#password\').val().length >= 6 && $(\'#password\').val().length <= 12;
 37                     var isID = $(\'#ids\').val().length > 0 && $(\'#ids\').val().length <= 18;
 38                     if (islen && isID) {
 39                         $.ajax({
 40                             async: true,
 41                             type: "post",
 42                             url: "http://localhost:8080/AppServer/MainServlet.action?ajaxType=jsonp&Type=save",
 43                             dataType: "jsonp",
 44                             jsonpCallback: "jsonpCallback",
 45                             jsonp: "callback",
 46                             data: {
 47                                 account: $(\'#account\').val(),
 48                                 passwords: $(\'#password\').val(),
 49                                 phone: $(\'#phone\').val(),
 50                                 email: $(\'#email\').val(),
 51                                 userId: $(\'#ids\').val(),
 52                                 userName: $(\'#name\').val(),
 53                                 sex: $(\'#sex\').val(),
 54                             },
 55                             success: function(server) {
 56                                 if (server.is) {
 57                                     alert("修改成功!");
 58                                     $(\'#div2\').hide(1500);
 59                                 } else {
 60                                     alert("修改失败!");
 61                                 }
 62                             },
 63                             error: function(server) {
 64                                 alert("连接服务器失败!");
 65                             },
 66                         });
 67                     } else {
 68                         if (!isID) {
 69                             alert(\'请输入正确的身份证!\');
 70                         } else if (!islen) {
 71                             alert(\'密码长度不一致\');
 72                         } else {
 73                             alert(\'请输入合法的信息!\');
 74                         }
 75                     }
 76                 });
 77                 $(\'#cancel\').click(function() {
 78                     $.ajax({
 79                         url: "http://localhost:8080/AppServer/MainServlet.action?ajaxType=jsonp&Type=cancel",
 80                         dataType: "jsonp",
 81                         jsonpCallback: "jsonpCallback",
 82                         jsonp: "callback",
 83                         data: {
 84                             account: accounts,
 85                         },
 86                         success: function(server) {
 87                             if (server.is) {
 88                                 alert("注销成功!");
 89                                 $(location).attr(\'href\', \'index.html\');
 90                             } else {
 91                                 alert("注销失败!");
 92                             }
 93                         },
 94                         error: function(server) {
 95                             alert("连接服务器失败!");
 96                         },
 97                     });
 98                 });
 99                 $(\'#all\').click(function() {
100                     $(\'#div3\').show(1500);
101                     $(\'#div2\').hide(1500);
102                     $.ajax({
103                         url: "http://localhost:8080/AppServer/MainServlet.action?ajaxType=jsonp&Type=all",
104                         dataType: "jsonp",
105                         jsonpCallback: "jsonpCallback",
106                         jsonp: "callback",
107                         success: function(server) {
108                             if (server.is) {
109                                 alert("查看成功!");
110                                 var arrData = [];
111                                 var arr = null;
112                                 for (i = 0; i < server.data.length; i++) {
113                                     if (arr == null) {
114                                         arr = new Array;
115                                     }
116                                     arr.push(server.data[i].userId);
117                                     arr.push(server.data[i].userName);
118                                     arr.push(server.data[i].account);
119                                     arr.push(server.data[i].phone);
120                                     arr.push(server.data[i].email);
121                                     arr.push(server.data[i].passwords);
122                                     arr.push(server.data[i].sex);
123                                     arrData.push(arr);
124                                     arr = null;
125                                 }
126                                 var td = "";
127                                 var table = "";
128                                 if(arrData != null){                                    
129                                     for(var i=0 ; i<arrData.length ; i++){
130                                         var tr = "<tr>";
131                                         for(var j=0 ; j<arrData[i].length; j++){
132                                             td += \'<td>\' + arrData[i][j] + \'</td>\';
133                                         }
134                                         var tr2 = "</tr>";
135                                         table += (tr + td + tr2);
136                                         td = "";
137                                     }
138                                     $(\'#bodys\').html(table);
139                                 }
140                             } else {
141                                 alert("查看失败!");
142                             }
143                         },
144                         error: function(server) {
145                             alert("连接服务器失败!");
146                         },
147                     });
148                 });
149             })

web.xml:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
 3   <display-name></display-name>
 4   <servlet>
 5     <servlet-name>LoginServlet</servlet-name>
 6     <servlet-class>com.yuw.servlet.LoginServlet</servlet-class>
 7   </servlet>
 8   <servlet>
 9     <servlet-name>RegisterServlet</servlet-name>
10     <servlet-class>com.yuw.servlet.RegisterServlet</servlet-class>
11   </servlet>
12   <servlet>
13     <servlet-name>MainServlet</servlet-name>
14     <servlet-class>com.yuw.servlet.MainServlet</servlet-class>
15   </servlet>
16   <servlet-mapping>
17     <servlet-name>LoginServlet</servlet-name>
18     <url-pattern>/LoginServlet.action</url-pattern>
19   </servlet-mapping>
20   <servlet-mapping>
21     <servlet-name>RegisterServlet</servlet-name>
22     <url-pattern>/RegisterServlet.action</url-pattern>
23   </servlet-mapping>
24   <servlet-mapping>
25     <servlet-name>MainServlet</servlet-name>
26     <url-pattern>/MainServlet.action</url-pattern>
27   </servlet-mapping>
28 </web-app>

 后台代码:

项目结构:

AccessData.java(与数据库交互)

  1 package com.yuw.jdbc;
  2 
  3 import java.io.IOException;
  4 import java.io.PrintWriter;
  5 import java.io.UnsupportedEncodingException;
  6 import java.sql.Connection;
  7 import java.sql.PreparedStatement;
  8 import java.sql.ResultSet;
  9 import java.sql.SQLException;
 10 import java.util.List;
 11 
 12 import javax.servlet.http.HttpServletRequest;
 13 import javax.servlet.http.HttpServletResponse;
 14 
 15 import com.yuw.servlet.example.JDBCDataBase;
 16 import com.yuw.transfer.DataTransfer;
 17 
 18 /**
 19  * 
 20  * @author Yuw
 21  * @data 2017-12-20
 22  */
 23 public abstract class AccessData {
 24     public static final int ONE = 1;
 25     protected Connection connection = null;
 26     protected PreparedStatement preparedStatement = null;
 27     protected ResultSet resultSet = null;
 28     // 接收数据
 29     protected List<Object> listDataReceive = null;
 30     public AccessData() {
 31 
 32     }
 33     /*
 34      * @dataBase 数据库连接
 35      * @dataTransfer 获得每次连接的数据信息
 36      */
 37     public void connectionJDBC(JDBCDataBase dataBase,DataTransfer<List<Object>> dataTransfer) {
 38         if(this.connection == null){
 39             this.connection = dataBase.example();
 40             this.listDataReceive = dataTransfer.transfer();
 41         }
 42     }
 43     /*
 44      * 删除
 45      */
 46     public int deleteData(String sql){
 47         int msg = 0;
 48         try {
 49             if(listDataReceive != null){
 50                 preparedStatement = connection.prepareStatement(sql);
 51                 int index = 1;
 52                 for(Object object : listDataReceive){
 53                     preparedStatement.setString(index++, (String)object);
 54                 }
 55                 msg = preparedStatement.executeUpdate();
 56             }
 57         } catch (SQLException e) {
 58             // TODO Auto-generated catch block
 59             e.printStackTrace();
 60         }finally{
 61             close();
 62         }
 63         return msg;
 64     }
 65     /*
 66      * 插入
 67      */
 68     public int insertData(String sql){
 69         int msg = 0;
 70         try {
 71             if(listDataReceive != null){
 72                 preparedStatement = connection.prepareStatement(sql);
 73                 int index = 1;
 74                 for(Object object : listDataReceive){
 75                     preparedStatement.setString(index++, (String)object);
 76                 }
 77                 msg = preparedStatement.executeUpdate();
 78             }
 79         } catch (SQLException e) {
 80             // TODO Auto-generated catch block
 81             e.printStackTrace();
 82         }finally{
 83             close();
 84         }
 85         return msg;
 86         
 87     }
 88     /*
 89      * 查询
 90      */
 91     public int selectData(String sql){
 92         PreparedStatement preparedStatement = setPreparedStatement(sql);
 93         try {
 94             if(listDataReceive != null){
 95                 int index = 1;
 96                 for(Object object : listDataReceive){
 97                     preparedStatement.setString(index++, (String)object);                
 98                     System.out.println((String)object);                
 99                 }
100                 resultSet = preparedStatement.executeQuery();
101                 return returnONE(resultSet);            
102             }
103             
104         } catch (SQLException e) {
105             // TODO Auto-generated catch block
106             e.printStackTrace();
107         }finally{
108             close();
109         }
110         return 0;
111         
112     }
113     /*
114      * 判断结果集是否只有一行
115      */
116     public int returnONE(ResultSet resultSet){
117         try {
118             resultSet.last();
119             if(resultSet.getRow() == ONE){
120                 return ONE;
121             }
122         } catch (SQLException e) {
123             // TODO Auto-generated catch block
124             e.printStackTrace();
125         }
126         return 0;
127         
128     }
129     
130     public PreparedStatement setPreparedStatement(String sql){
131         try {
132             if(this.preparedStatement == null){
133                 this.preparedStatement = connection.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
134             }
135         } catch (SQLException e) {
136             // TODO Auto-generated catch block
137             e.printStackTrace();
138         }
139         return preparedStatement;
140         
141     }
142     /*
143      * 处理乱码
144      */
145     public String toCharacterEncoding(String str) throws UnsupportedEncodingException{
146         if(str == null){
147             System.out.println("请传参");
148         }
149         return new String(str.getBytes("iso-8859-1"),"utf-8");
150         
151     }
152     /*
153      * 关闭连接
154      */
155     public void close(){
156         if(preparedStatement != null){
157             try {
通过flask实现web页面简单的增删改查

node实现简单的增删改查接口

Vue结合后台的增删改案例

基于maven+ssm的增删改查之添加员工实现

项目一众筹网02_5_管理员维护(分页 和 管理员的增删改查)——管理员维护我们使用同步,角色维护我们使用异步(ajax)

AngularJS 实现管理系统中的增删改查