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 2 3 4 56 7 15 22 23 24 请点击下面的按钮,通过 jQuery AJAX 改变这段文本。
25 26 27
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 4 5 6 7 863 64Insert title here 9 53 54 55 56
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 ZhueServlet15 */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 stub27 }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 stub70 doGet(request, response);71 }72 //判断传入的参数有没有空的方法,只要有空的就返回false73 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 ZBK12 */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 * 数据库地址URL28 */29 public static final String URL = "jdbc:oracle:thin:@localhost:1521:xe";30 31 /**32 * 获取数据库连接33 * @return34 */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 args84 * @return85 */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 @Override33 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 @Override42 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 @Override33 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 SelectAllProServlet17 */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 stub28 }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 stub64 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 SelectCityServlet18 */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 stub29 }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 * 拼接字符串传回json44 * 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 //导包调用方法,传回json64 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 stub80 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 SelectareaServlet19 */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 stub30 }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 stub60 doGet(request, response);61 }62 63 }
准备页面和ajax
1 <%@ page language="java" contentType="text/html; charset=utf-8" 2 pageEncoding="utf-8"%> 3 4 5 6 7 8 9Insert title here 10 18 19 2021 22 23 2425 26
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("");//初始化下拉框11 $("#city").append("");//初始化下拉框12 $("#area").append("");//初始化下拉框13 for (var i = 0; i < data.result.length; i++) {14 $("#province").append(15 "");18 }19 20 } else {21 alert("后台没有取出数据 !");22 }23 },24 error : function(msg) {25 console.log(msg);26 }27 });28 29 30 // 加载市级31 $("#province").change(32 function() {33 $("#area").empty();//清空,否则会导致多次查询的堆积起来34 $("#area")35 .append("");36 var provinceid = $(this).val();37 $.ajax({38 type : "post",39 url : "SelectCityServlet",40 data : {41 provinceid : provinceid//传出的参数类型是provinceid,值是provinceid42 },43 dataType : "json",44 success : function(data) {45 if (data.success) {46 $("#city").empty();47 $("#city")48 .append("");49 for (var i = 0; i < data.result.length; i++) {50 $("#city").append(51 "");55 }56 } else {57 alert("后台没有取出数据 !");58 }59 },60 error : function(msg) {61 console.log(msg);62 }63 });64 });65 66 67 // 加载区68 $("#city").change(69 function() {70 var cityid = $(this).val();71 $.ajax({72 type : "post",73 url : "SelectareaServlet",74 data : {75 cityid : cityid76 },77 dataType : "json",78 success : function(data) {79 if (data.success) {80 $("#area").empty();//清空,否则会导致多次查询的堆积起来81 $("#area")82 .append("");83 for (var i = 0; i < data.result.length; i++) {84 $("#area").append(85 "");89 }90 } else {91 alert("后台没有取出数据 !");92 }93 },94 error : function(msg) {95 console.log(msg);96 }97 });98 });99 });