Ajax
ajax:AJAX 是与服务器交换数据的艺术,它在不重载全部页面的情况下,实现了对部分网页的更新
AJAX:Asynchronous JavaScript and XML,异步 javascript和 XML,带来用户体验改变,是web优化一种主要手段
AJAX = DHTML (HTML、CSS、JavaScript ) + XMLHttpRequest 对象
传统web交互模型,浏览器直接将请求发送给服务器,服务器回送响应,直接发给浏览器, Ajax交互模型,浏览器首先将请求 发送 Ajax引擎(以XMLHttpRequest为核心),AJax引擎再将请求发送给 服务器,服务器回送响应先发给Ajax引擎,再由引擎传给浏览器显示
1、同步交互模式,客户端提交请求,等待,在响应回到客户端前,客户端无法进行其他操作
2、异步交互模型,客户端将请求提交给Ajax引擎,客户端可以继续操作,由Ajax引擎来完成与服务武器端通信,当响应回来后,Ajax引擎会更新客户页面,在客户端提交请求后,用户可以继续操作,而无需等待 。
Google : suggest建议、邮件定时保存、map地图
jQuery 与 AJAX
jQuery 提供多个与 AJAX 有关的方法。
通过 jQuery AJAX 方法,我们能够使用 HTTP Get 和 HTTP Post 从远程服务器上请求文本、HTML、XML 或 JSON - 同时您能够把这些外部数据直接载入网页的被选元素中。
四种Ajax
1.
$("").load("url地址",data参数,function(){回调函数,返回的时候执行});
load() 方法从服务器加载数据,并把返回的数据放入被选元素中。
必需: URL 参数:规定希望加载的 URL。
可选: data 参数:规定与请求一同发送的查询字符串键/值对集合。
可选: callback 参数:是 load() 方法完成后所执行的函数名称。
1 DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8" /> 5 <title>title> 6 <script src="js/jquery-3.2.1.min.js">script> 7 <style type="text/css"> 8 div{ 9 width: 60px; 10 height: 60px; 11 background-color: aquamarine; 12 margin: 2px; 13 } 14 style> 15 <script> 16 $(document).ready(function(){ 17 $("#btn1").click(function(){ 18 $('#test').load('js/jquery-3.2.1.min.js'); 19 }) 20 }) 21 script> 22 head> 23 <body> 24 <h3 id="test">请点击下面的按钮,通过 jQuery AJAX 改变这段文本。h3> 25 <button id="btn1" type="button">获得外部的内容button> 26 body> 27 html>
2.
$.get(...);
3.
$.post(...);
两种在客户端和服务器端进行请求-响应的常用方法是:GET 和 POST。
- GET - 从指定的资源请求数据
- POST - 向指定的资源提交要处理的数据
GET 基本上用于从服务器获得(取回)数据。注释:GET 方法可能返回缓存数据。
POST 也可用于从服务器获取数据。不过,POST 方法不会缓存数据,并且常用于连同请求一起发送数据。
4.
$.ajax({
url:"传给谁",
data:(参数),
type:"post/get",
dateType:"html/text/json",
success:function(data){
},
error:function(msg){
}
});
注册页面,以及失去焦点验证用户名是否存在
1 <%@ page language="java" contentType="text/html; charset=utf-8" 2 pageEncoding="utf-8"%> 3 DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 7 <script type="text/javascript" src="js/jquery-3.2.1.min.js">script> 8 <title>Insert title heretitle> 9 <script type="text/javascript"> 10 $(function() { 11 $("#btn_log").click(function() { 12 $.ajax({ 13 type:"post", 14 url:"ZhueServlet", 15 data:$("#formdata").serializeArray(), 16 dataType:"json",//返回的 17 success:function(data) { 18 if(data.success) { 19 window.location.href="denglu.jsp"; 20 } else { 21 alert(data.msg);//打印相应的错误信息 22 } 23 }, 24 error:function(msg) { 25 cosole.log(msg); 26 } 27 }); 28 }); 29 30 // 失去焦点验证用户名是否存在 31 $("#username").blur(function() { 32 var u_val = $("#username").val(); 33 34 $.ajax({ 35 type:"post", 36 url:"CheckUsername", 37 data:{username:u_val}, 38 dataType:"text", 39 success:function(data) { 40 if("no" == data) { 41 $("#msg").html("用户名已经存在"); 42 } else if("ok"==data) { 43 $("#msg").html("该用户名可以使用 !"); 44 } 45 }, 46 error:function(msg) { 47 cosole.log(msg);//在控制台打印错误信息48 } 49 }); 50 }); 51 }); 52 script> 53 head> 54 <body> 55 56 <form id="formdata"> 57 用户名:<input id="username" type="text" name="username"><span id="msg">span><br> 58 密码:<input type="password" name="password"><br> 59 确认密码:<input type="password" name="password1"><br> 60 真实姓名:<input type="text" name="realname"><br> 61 <a id="btn_log" href="#">提交a>><br> 62 form> 63 body> 64 html>
1 //注册逻辑 2 package com.servlet; 3 4 import java.io.IOException; 5 import javax.servlet.ServletException; 6 import javax.servlet.annotation.WebServlet; 7 import javax.servlet.http.HttpServlet; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse; 10 import com.util.MethodDal; 11 import com.util.User; 12 13 /** 14 * Servlet implementation class ZhueServlet 15 */ 16 @WebServlet("/ZhueServlet") 17 public class ZhueServlet extends HttpServlet { 18 19 private static final long serialVersionUID = 1L; 20 21 /** 22 * @see HttpServlet#HttpServlet() 23 */ 24 public ZhueServlet() { 25 super(); 26 // TODO Auto-generated constructor stub 27 } 28 29 /** 30 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 31 */ 32 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 33 //首先设置可以处理中文 34 request.setCharacterEncoding("utf-8"); 35 response.setCharacterEncoding("utf-8"); 36 response.setContentType("text/html; charset=utf-8"); 37 //获取传入的数据 38 String username=request.getParameter("username"); 39 String password=request.getParameter("password"); 40 String password1=request.getParameter("password1"); 41 String realname=request.getParameter("realname"); 42 43 System.out.println("a:"+username+password); 44 //调用方法判断传入的参数有没有空,都不为空才可以执行下去 45 if(checkParam(username,password,password1)){ 46 if(password.equals(password1)){ 47 MethodDal m=new MethodDal(); 48 if(m.selectName(username).equals("no")){//调用方法根据用户名查询,如果返回no说明数据库没有此用户名,可以注册 49 User user=new User();//实例化用户类并添加信息 50 user.setUsername(username); 51 user.setPassword(password); 52 m.insertData(user);//将实例化的用户传到添加用户的方法 53 response.getWriter().append("{\"success\":true}");//返回键值对,做相关判断,输出相关信息 54 }else{ 55 response.getWriter().append("{\"success\":false, \"msg\":\"1请正确输入\"}"); 56 } 57 }else{ 58 response.getWriter().append("{\"msg\":\"2请正确输入\"}"); 59 } 60 }else{ 61 response.getWriter().append("{\"msg\":\"3请正确输入\"}"); 62 } 63 } 64 65 /** 66 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 67 */ 68 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 69 // TODO Auto-generated method stub 70 doGet(request, response); 71 } 72 //判断传入的参数有没有空的方法,只要有空的就返回false 73 public boolean checkParam(String... args){//这样传参数代表参数个数不确定,传几个都可以 74 for(String s : args){ 75 if("".equals(s)||s==null){ 76 return false; 77 } 78 } 79 return true; 80 } 81 }
案例:省市区三级联动
准备util工具包,数据库链接设置,数据库操作工具类
1 package com.util; 2 //数据库设置 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.ResultSet; 6 import java.sql.SQLException; 7 import java.sql.Statement; 8 9 /** 10 * 数据库驱动连接类 11 * @author ZBK 12 */ 13 public class DBHelper { 14 /** 15 * 数据库用户名 16 */ 17 public static final String USERNAME = "test"; 18 /** 19 * 数据库密码 20 */ 21 public static final String PASSWORD = "test"; 22 /** 23 * 数据库驱动类 24 */ 25 public static final String DRIVER = "oracle.jdbc.OracleDriver"; 26 /** 27 * 数据库地址URL 28 */ 29 public static final String URL = "jdbc:oracle:thin:@localhost:1521:xe"; 30 31 /** 32 * 获取数据库连接 33 * @return 34 */ 35 public static Connection getConnection() { 36 Connection conn = null; 37 try { 38 Class.forName(DRIVER); 39 conn = DriverManager.getConnection(URL, USERNAME, PASSWORD); 40 } catch (ClassNotFoundException e) { 41 e.printStackTrace(); 42 } catch (SQLException e) { 43 e.printStackTrace(); 44 } 45 return conn; 46 } 47 48 /** 49 * 释放资源 50 * @param conn 数据库连接对象 51 * @param sm Statement对象 52 * @param rs ResultSet结果集对象 53 */ 54 public static void destroy(Connection conn, Statement sm, ResultSet rs) { 55 if (conn != null) { 56 try { 57 conn.close(); 58 } catch (SQLException e) { 59 e.printStackTrace(); 60 } 61 conn = null; 62 } 63 if (sm != null) { 64 try { 65 sm.close(); 66 } catch (SQLException e) { 67 e.printStackTrace(); 68 } 69 sm = null; 70 } 71 if (rs != null) { 72 try { 73 rs.close(); 74 } catch (SQLException e) { 75 e.printStackTrace(); 76 } 77 rs = null; 78 } 79 } 80 81 /** 82 * 验证前台传入的参数是否为空 83 * @param args 84 * @return 85 */ 86 public static boolean checkParam(String... args) { 87 for (String s : args) { 88 if (s == null || s.trim().length() < 1) { 89 return false; 90 } 91 } 92 return true; 93 } 94 }
1 package com.util; 2 3 import java.sql.Connection; 4 import java.sql.PreparedStatement; 5 import java.sql.ResultSet; 6 import java.sql.SQLException; 7 import java.util.ArrayList; 8 import java.util.List; 9 10 import com.model.Area; 11 import com.model.City; 12 import com.model.Province; 13 14 public class DataBaseUtil { 15 private Connection conn; 16 private PreparedStatement ps; 17 private ResultSet rs; 18 19 /** 20 * 初始化数据库链接 21 */ 22 public void init(String sql) { 23 conn = DBHelper.getConnection(); 24 try { 25 ps = conn.prepareStatement(sql); 26 } catch (SQLException e) { 27 e.printStackTrace(); 28 } 29 } 30 31 /** 32 * 查询所有省信息 33 * 34 */ 35 public ListSelectAllPro() { 36 String sql = "select * from C_PROVINCES t"; 37 init(sql); 38 List plist = null; 39 try { 40 rs = ps.executeQuery(); 41 if(rs != null) { 42 plist = new ArrayList (); 43 while(rs.next()) { 44 Province p = new Province(); 45 p.setId(rs.getInt("id")); 46 p.setProvince(rs.getString("province")); 47 p.setProvinceid(rs.getString("provinceid")); 48 plist.add(p); 49 } 50 } 51 } catch (SQLException e) { 52 e.printStackTrace(); 53 } 54 55 return plist; 56 } 57 58 public List SelectCity(String provinceid) { 59 String sql = "select * from C_CITIES t where t.provinceid=?"; 60 init(sql); 61 List clist = null; 62 try { 63 ps.setString(1, provinceid); 64 rs = ps.executeQuery(); 65 if(rs!=null) { 66 clist = new ArrayList (); 67 while(rs.next()) { 68 City city = new City(); 69 city.setId(rs.getInt("id")); 70 city.setCity(rs.getString("city")); 71 city.setCityid(rs.getString("cityid")); 72 city.setProvinceid(rs.getString("provinceid")); 73 clist.add(city); 74 } 75 } 76 } catch (SQLException e) { 77 e.printStackTrace(); 78 } 79 80 return clist; 81 } 82 83 public List SelectArea(String cityid) { 84 String sql = "select * from C_AREAS t where t.cityid=?"; 85 init(sql); 86 List alist = null; 87 try { 88 ps.setString(1, cityid); 89 rs = ps.executeQuery(); 90 if(rs!=null) { 91 alist = new ArrayList(); 92 while(rs.next()) { 93 Area a = new Area(); 94 a.setId(rs.getInt("id")); 95 a.setArea(rs.getString("area")); 96 a.setAreaid(rs.getString("areaid")); 97 a.setCityid(rs.getString("cityid")); 98 alist.add(a); 99 } 100 } 101 } catch (SQLException e) { 102 e.printStackTrace(); 103 } 104 105 return alist; 106 } 107 }
准备model包,包含省市区三个类
1 package com.model; 2 3 public class Province { 4 private int id; 5 private String provinceid; 6 private String province; 7 8 public int getId() { 9 return id; 10 } 11 12 public void setId(int id) { 13 this.id = id; 14 } 15 16 public String getProvinceid() { 17 return provinceid; 18 } 19 20 public void setProvinceid(String provinceid) { 21 this.provinceid = provinceid; 22 } 23 24 public String getProvince() { 25 return province; 26 } 27 28 public void setProvince(String province) { 29 this.province = province; 30 } 31 32 @Override 33 public String toString() { 34 return "Province [id=" + id + ", provinceid=" + provinceid + ", province=" + province + "]"; 35 } 36 37 }
1 package com.model; 2 3 public class City { 4 private int id; 5 private String cityid; 6 private String city; 7 private String provinceid; 8 9 public int getId() { 10 return id; 11 } 12 13 public void setId(int id) { 14 this.id = id; 15 } 16 17 public String getCityid() { 18 return cityid; 19 } 20 21 public void setCityid(String cityid) { 22 this.cityid = cityid; 23 } 24 25 public String getCity() { 26 return city; 27 } 28 29 public void setCity(String city) { 30 this.city = city; 31 } 32 33 public String getProvinceid() { 34 return provinceid; 35 } 36 37 public void setProvinceid(String provinceid) { 38 this.provinceid = provinceid; 39 } 40 41 @Override 42 public String toString() { 43 return "City [id=" + id + ", cityid=" + cityid + ", city=" + city + ", provinceid=" + provinceid + "]"; 44 } 45 46 }
1 package com.model; 2 3 public class Area { 4 private int id; 5 private String areaid; 6 private String area; 7 private String cityid; 8 public int getId() { 9 return id; 10 } 11 public void setId(int id) { 12 this.id = id; 13 } 14 public String getAreaid() { 15 return areaid; 16 } 17 public void setAreaid(String areaid) { 18 this.areaid = areaid; 19 } 20 public String getArea() { 21 return area; 22 } 23 public void setArea(String area) { 24 this.area = area; 25 } 26 public String getCityid() { 27 return cityid; 28 } 29 public void setCityid(String cityid) { 30 this.cityid = cityid; 31 } 32 @Override 33 public String toString() { 34 return "Area [id=" + id + ", areaid=" + areaid + ", area=" + area + ", cityid=" + cityid + "]"; 35 } 36 }
准备处理逻辑,三个Servlet
1 package com.servlet; 2 3 import java.io.IOException; 4 import java.util.List; 5 6 import javax.servlet.ServletException; 7 import javax.servlet.annotation.WebServlet; 8 import javax.servlet.http.HttpServlet; 9 import javax.servlet.http.HttpServletRequest; 10 import javax.servlet.http.HttpServletResponse; 11 12 import com.model.Province; 13 import com.util.DataBaseUtil; 14 15 /** 16 * Servlet implementation class SelectAllProServlet 17 */ 18 @WebServlet("/SelectAllProServlet") 19 public class SelectAllProServlet extends HttpServlet { 20 private static final long serialVersionUID = 1L; 21 22 /** 23 * @see HttpServlet#HttpServlet() 24 */ 25 public SelectAllProServlet() { 26 super(); 27 // TODO Auto-generated constructor stub 28 } 29 30 /** 31 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 32 */ 33 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 34 response.setCharacterEncoding("utf-8"); 35 //初始化数据库操作类 36 DataBaseUtil db = new DataBaseUtil(); 37 38 Listplist = db.SelectAllPro(); 39 40 String json = "{\"success\":"; 41 42 if (plist != null) { 43 json += "true,\"result\":";//result是一个键,他得值是后面的数组,这个数组包含了一串键值对 44 json += "["; 45 for (int i = 0; i < plist.size(); i++) { 46 json += "{\"id\":\"" + plist.get(i).getId() + "\",\"province\":\"" + plist.get(i).getProvince() 47 + "\",\"provinceid\":\"" + plist.get(i).getProvinceid() + "\"}"; 48 if (i != plist.size() - 1) { 49 json += ","; 50 } 51 } 52 json += "]}"; 53 } else { 54 json += "false}"; 55 } 56 response.getWriter().append(json); 57 } 58 59 /** 60 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 61 */ 62 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 63 // TODO Auto-generated method stub 64 doGet(request, response); 65 } 66 67 }
1 package com.servlet; 2 3 import java.io.IOException; 4 import java.util.List; 5 6 import javax.servlet.ServletException; 7 import javax.servlet.annotation.WebServlet; 8 import javax.servlet.http.HttpServlet; 9 import javax.servlet.http.HttpServletRequest; 10 import javax.servlet.http.HttpServletResponse; 11 12 import com.alibaba.fastjson.JSONObject; 13 import com.model.City; 14 import com.util.DataBaseUtil; 15 16 /** 17 * Servlet implementation class SelectCityServlet 18 */ 19 @WebServlet("/SelectCityServlet") 20 public class SelectCityServlet extends HttpServlet { 21 private static final long serialVersionUID = 1L; 22 23 /** 24 * @see HttpServlet#HttpServlet() 25 */ 26 public SelectCityServlet() { 27 super(); 28 // TODO Auto-generated constructor stub 29 } 30 31 /** 32 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 33 */ 34 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 35 response.setCharacterEncoding("utf-8"); 36 37 String provinceid = request.getParameter("provinceid"); 38 39 DataBaseUtil db = new DataBaseUtil(); 40 41 Listclist = db.SelectCity(provinceid); 42 /* 43 * 拼接字符串传回json 44 * System.out.println(provinceid); 45 String json = "{\"success\":"; 46 47 if (clist != null) { 48 json += "true,\"result\":"; 49 json += "["; 50 for (int i = 0; i < clist.size(); i++) { 51 json += "{\"id\":\"" + clist.get(i).getId() + "\",\"city\":\"" + clist.get(i).getCity() 52 + "\",\"cityid\":\"" + clist.get(i).getCityid() + "\"}"; 53 if (i != clist.size() - 1) { 54 json += ","; 55 } 56 } 57 json += "]}"; 58 } else { 59 json += "false}"; 60 } 61 62 response.getWriter().append(json);*/ 63 //导包调用方法,传回json 64 JSONObject jo = new JSONObject(); 65 66 if(clist!=null) { 67 jo.put("success", true); 68 jo.put("result", clist); 69 } else { 70 jo.put("success", false); 71 } 72 response.getWriter().append(jo.toJSONString()); 73 } 74 75 /** 76 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 77 */ 78 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 79 // TODO Auto-generated method stub 80 doGet(request, response); 81 } 82 83 }
1 package com.servlet; 2 3 import java.io.IOException; 4 import java.util.List; 5 6 import javax.servlet.ServletException; 7 import javax.servlet.annotation.WebServlet; 8 import javax.servlet.http.HttpServlet; 9 import javax.servlet.http.HttpServletRequest; 10 import javax.servlet.http.HttpServletResponse; 11 12 import com.alibaba.fastjson.JSONObject; 13 import com.model.Area; 14 import com.model.City; 15 import com.util.DataBaseUtil; 16 17 /** 18 * Servlet implementation class SelectareaServlet 19 */ 20 @WebServlet("/SelectareaServlet") 21 public class SelectareaServlet extends HttpServlet { 22 private static final long serialVersionUID = 1L; 23 24 /** 25 * @see HttpServlet#HttpServlet() 26 */ 27 public SelectareaServlet() { 28 super(); 29 // TODO Auto-generated constructor stub 30 } 31 32 /** 33 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 34 */ 35 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 36 response.setCharacterEncoding("utf-8"); 37 38 String cityid = request.getParameter("cityid"); 39 40 DataBaseUtil db = new DataBaseUtil(); 41 42 List alist = db.SelectArea(cityid); 43 JSONObject jo = new JSONObject(); 44 45 if(alist!=null) { 46 jo.put("success", true); 47 jo.put("result", alist); 48 } else { 49 jo.put("success", false); 50 } 51 response.getWriter().append(jo.toJSONString()); 52 53 } 54 55 /** 56 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 57 */ 58 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 59 // TODO Auto-generated method stub 60 doGet(request, response); 61 } 62 63 }
准备页面和ajax
1 <%@ page language="java" contentType="text/html; charset=utf-8" 2 pageEncoding="utf-8"%> 3 DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 7 <script type="text/javascript" src="js/jquery-3.2.1.min.js">script> 8 <script type="text/javascript" src="js/index.js">script> 9 <title>Insert title heretitle> 10 <style type="text/css"> 11 #pdiv{ 12 margin:30px auto; 13 width:600px; 14 height:auto; 15 border:1px black solid; 16 } 17 style> 18 head> 19 <body> 20 <div id="pdiv"> 21 <select id="province">select> 22 <select id="city">select> 23 <select id="area">select> 24 div> 25 body> 26 html>
1 $(function() { 2 //访问页面显示省的信息 3 $.ajax({ 4 type:"post", 5 url:"SelectAllProServlet", 6 //data此处不需要 7 dataType:"json", 8 success : function(data) { 9 if (data.success) { 10 $("#province").append("<option vlaue='-1'>==请选择==option>");//初始化下拉框 11 $("#city").append("<option vlaue='-1'>==请选择==option>");//初始化下拉框 12 $("#area").append("<option vlaue='-1'>==请选择==option>");//初始化下拉框 13 for (var i = 0; i < data.result.length; i++) { 14 $("#province").append( 15 "