10-ajax技术简介
一.ajax是什么?
是网页中的异步刷新技术。其核心是js+xml
二.执行过程
1.js的核心对象XMLHttpRequest是一个具备像后台发送请求的一个对象
2.XMLHttpRequest可以异步发送请求
3.指定回调函数
4.等待后台响应,这个过程是异步的。此时网页中的其他元素是处于可用状态
5.响应得到后会执行回调函数来局部刷新网页
三。好处:
1.用户体验感增强
2.不用等待操作结果
3.提高带宽的使用率
四。Json数据的使用
1.json是一种纯字符串的数据格式,可以用来描述复杂的对象或数组
2.使用场景:可以将java对象和json格式的数据互相装换
3.使用步骤,在项目中要加入json转换的jar包
实例:验证用户名重复+省市区下拉列表联动
checkUsername.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE html> <html> <head> <base href="<%=basePath%>"/> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script type="text/javascript" src="js/jquery-3.2.1.js"></script> <title>Insert title here</title> </head> <script type="text/javascript"> var xmlhttp;//全局变量 function checkName(value){ //1.要获取XMLHttpRequest对象 if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); }else{// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } //指定回调函数 xmlhttp.onreadystatechange=reback;//回调函数是专门处理后台响应后的数据变化 //打开连接 指定提交方式,指定url地址 指定是否异步(true为异步 false同步) //js中向后台传中文参数需要转码encodeURI(\'张三\') xmlhttp.open("post","ajaxCheckName?name="+encodeURI(value),true); //设置传参方式为表单提交 xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); //发送请求 xmlhttp.send(); } function reback(){ //判断各种响应状态 if (xmlhttp.readyState==4 && xmlhttp.status==200){ //获取后台响应过来的数据,只能接收字符串 if(xmlhttp.responseText==\'true\'){//用户名重复 document.getElementById(\'mess_name\').style.color="red"; document.getElementById(\'mess_name\').innerHTML="用户名重复"; }else{ document.getElementById(\'mess_name\').style.color="green"; document.getElementById(\'mess_name\').innerHTML="用户可用"; } } } //Jquery的方式来做ajax,效果同上 $("document").ready(function (){ $("#username").bind("blur",function(){ $.post("ajaxCheckName?name="+this.value,function(data){ if(data=="true"){ $("#mess_name").css("color","red"); $("#mess_name").html("用户名重复"); }else{ $("#mess_name").css("color","green"); $("#mess_name").html("用户名可用"); } }); }); }); $("document").ready(function (){ $.post("address?type=province",function(data){ var str = ""; console.log(data); $.each(JSON.parse(data),function(i,address){ console.log(i,address.id,address.name,address.type); str += "<option value=\'"+address.id+"\'>"+address.name+"</option>"; }); $("#pro").html(str); }); $("#pro").bind("change",function(){ $.post("address?type=city&proid="+this.value,function(data){ var str = ""; console.log(data); $.each(JSON.parse(data),function(i,address){ console.log(i,address.id,address.name,address.type); str += "<option value=\'"+address.id+"\'>"+address.name+"</option>"; }); $("#city").html(str); }); }); $("#city").bind("change",function(){ $.post("address?type=area&cityid="+this.value,function(data){ var str = ""; console.log(data); $.each(JSON.parse(data),function(i,address){ console.log(i,address.id,address.name,address.type); str += "<option value=\'"+address.id+"\'>"+address.name+"</option>"; }); $("#area").html(str); }); }); }); </script> <body> <button onclick="checkName()">测试</button> <div id="myDiv"></div> <input name="" onblur="checkName(this.value)"> <span id="err" style="color: red;"></span> <br> <input> <div align="center"> <form action=""> 用户名:<input id="username"><span id="mess_name"></span><br> 密码:<input><br> 地址:<select id="pro"> <option>请选择省份</option> </select> <select id="city"> <option>请选择城市</option> </select> <select id="area"> <option>请选择地区</option> </select> </form> </div> </body> </html>
AjaxCheckNameServlet.java
package com.control; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/ajaxCheckName") public class AjaxCheckNameServlet extends HttpServlet{ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String name = req.getParameter("name"); PrintWriter out = resp.getWriter();//获取输出流 if("海文".equals(name)){//用户名重复 out.print("true"); }else{ out.print("false"); } out.flush(); out.close(); } }
AddressServlet.java
package com.control; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; 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.pojo.Address; import com.service.AddressService; import com.service.IAddressService; import net.sf.json.JSONArray; @WebServlet("/address") public class AddressServlet extends HttpServlet{ IAddressService addSer = new AddressService(); @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String type = req.getParameter("type"); List<Address> list = null; if("province".equals(type)){//获取省份数据 list = addSer.getAllProvince(); } if("city".equals(type)){//获取城市 String proid = req.getParameter("proid"); list = addSer.getChildByParentid(proid); } if("area".equals(type)){//获取地区 String cityid = req.getParameter("cityid"); list = addSer.getChildByParentid(cityid); } //将java对象转换成json数据 JSONArray json = JSONArray.fromObject(list); //将json响应给前台 resp.setCharacterEncoding("UTF-8");//解决响应的中文乱码问题 PrintWriter out = resp.getWriter(); out.print(json.toString()); out.flush(); out.close(); } }