Ajax
一、Ajax开发步骤:
1.得到XMLHttpRequest对象。
var xmlhttp=null; if (window.XMLHttpRequest) {// code for all new browsers xmlhttp=new XMLHttpRequest(); } else if (window.ActiveXObject) {// code for IE5 and IE6 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }
2.注册回调函数 xmlhttp.onreadystatechange=function(){};
3.open 只是用于设置请求方式 以及url,它不发送请求。
4.send 它是用于发送请求的。send(null);null代表没有参数 如果有参数可以写成:"username=tom&password=123"。
5.在回调函数中处理数据
5.1.XMLHttpRequest对象有一个属性 readyState,它代表的是XMLHttpRequest对象的状态。
0).代表XMLHttpRequest对象创建
1).open操作
2).send操作
3).接收到了响应数据,但是只有响应头,正文还没有接收。
4).所有http响应接收完成。
5.2.status 由服务器返回的 HTTP 状态代码,如 200 表示成功。
5.3.在回调函数中可以通过以下方式获取服务器返回的数据。1.responseText 2.responseXML
二、Ajax实例1:
<script type="text/javascript"> //第一步:得到XMLHttpRequest对象. var xmlhttp = null; if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); //针对于现在的浏览器包括IE7以上版本 } else if (window.ActiveXObject) { //针对于IE5,IE6版本 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } //2.设置回调函数 xmlhttp.onreadystatechange=function(){ //5.处理响应数据 当信息全部返回,并且是成功 if(xmlhttp.readyState==4&&xmlhttp.status==200){ alert(xmlhttp.responseText); } }; //3.open xmlhttp.open("GET","http://localhost/day23_3/ajax1"); //4.发送请求 send xmlhttp.send(null); </script>
三、关于ajax操作中请求参数的设置问题:
1.对于get请求方式,参数设置
直接在url后面拼接 例如:"${pageContext.request.contextPath}/ajax2?name=tom"
2.对于post请求方式,参数设置
xmlhttp.open("POST","${pageContext.request.contextPath}/ajax2");
xmlhttp.send("name=tom");
注意:如果是post请求方式,还需要设置一个http请求头。xmlhttp.setRequestHeader("","");
例如: xmlhttp.open("POST","${pageContext.request.contextPath}/ajax2");
xmlhttp.setRequestHeader("content-type","application/x-www-form-urlencoded");
xmlhttp.send("name=tom");
四、Ajax实例2:
版本1: 1.创建一个Product类
package cn.itcast.domain; public class Product { private int id; private String name; private double price; private String type; public String getType() { return type; } public void setType(String type) { this.type = type; } public Product() { super(); } public Product(int id, String name, double price) { super(); this.id = id; this.name = name; this.price = price; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } }
2.创建ajax.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>ajax开发---显示商品信息</title> <script type="text/javascript" src="${pageContext.request.contextPath}/my.js"></script> <script type="text/javascript"> window.onload = function() { //得到id=t的文本框 var p = document.getElementById("p"); p.onclick = function() { //第一步:得到XMLHttpRequest对象. var xmlhttp = getXmlHttpRequest(); //2.设置回调函数 xmlhttp.onreadystatechange = function() { //5.处理响应数据 当信息全部返回,并且是成功 if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { var msg = xmlhttp.responseText; document.getElementById("d").innerHTML = msg; } }; //post请求方式,参数设置 xmlhttp.open("GET", "${pageContext.request.contextPath}/ajax4"); xmlhttp.send(null); }; }; </script> </head> <body> <a href="javascript:void(0)" id="p">显示商品信息</a> <div id="d"></div> </body> </html>
3.在AjaxServlet中将List<Product>中的数据,手动拼接成了html代码,写回到浏览器端。
public class AjaxServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); List<Product> ps = new ArrayList<Product>(); ps.add(new Product(1, "洗衣机", 1800)); ps.add(new Product(2, "电视机", 3800)); ps.add(new Product(3, "空调", 5800)); PrintWriter out = response.getWriter(); StringBuilder builder = new StringBuilder(); builder.append("<table border='1'><tr><td>商品编号</td><td>商品名称</td><td>商品价格</td></tr>"); for (Product p : ps) { builder.append("<tr><td>" + p.getId() + "</td><td>" + p.getName() + "</td><td>" + p.getPrice() + "</td></tr>"); } builder.append("</table>"); out.print(builder.toString()); out.flush(); out.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
版本2: 1.创建一个product.jsp页面,在页面上去组装table,直接将数据返回了。
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <table border='1'> <tr> <td>商品编号</td> <td>商品名称</td> <td>商品价格</td> </tr> <c:forEach items="${ps}" var="p"> <tr> <td>${p.id }</td> <td>${p.name }</td> <td>${p.price }</td> </tr> </c:forEach> </table>
2.AjaxServlet
public class AjaxServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); List<Product> ps = new ArrayList<Product>(); ps.add(new Product(1, "洗衣机", 1800)); ps.add(new Product(2, "电视机", 3800)); ps.add(new Product(3, "空调", 5800)); request.setAttribute("ps", ps); request.getRequestDispatcher("/product.jsp").forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
版本3:在服务器端得到数据,只将要显示的内容返回,而不返回html代码,而html代码的拼接,在浏览器端完成-引入Json。
1.创建ajax.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>ajax开发---显示商品信息(json)</title> <script type="text/javascript" src="${pageContext.request.contextPath}/my.js"></script> <script type="text/javascript"> window.onload = function() { //得到id=t的文本框 var p = document.getElementById("p"); p.onclick = function() { //第一步:得到XMLHttpRequest对象. var xmlhttp = getXmlHttpRequest(); //2.设置回调函数 xmlhttp.onreadystatechange = function() { //5.处理响应数据 当信息全部返回,并且是成功 if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { var json = eval(xmlhttp.responseText); var msg="<table border='1'><tr><td>商品编号</td><td>商品名称</td><td>商品价格</td></tr>"; for(var i=0;i<json.length;i++){ msg+="<tr><td>"+json[i].id+"</td><td>"+json[i].name+"</td><td>"+json[i].price+"</td></tr>"; } msg+="</table>"; document.getElementById("d").innerHTML=msg; } }; //post请求方式,参数设置 xmlhttp.open("GET", "${pageContext.request.contextPath}/ajax5"); xmlhttp.send(null); }; }; </script> </head> <body> <a href="javascript:void(0)" id="p">显示商品信息</a> <div id="d"></div> </body> </html>
2.创建AjaxServlet
public class Ajax5Servlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); List<Product> ps = new ArrayList<Product>(); ps.add(new Product(1, "洗衣机", 1800)); ps.add(new Product(2, "电视机", 3800)); ps.add(new Product(3, "空调", 5800)); // 返回的是json数据 PrintWriter out = response.getWriter(); String json = JSONArray.fromObject(ps).toString(); out.print(json); out.flush(); out.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
五、Json的使用
1.导包(6个包)
2.将java对象转换成json
2.1.对于数组,List集合,要想转换成json:JSONArray.fromObject(java对象); ["value1","value2"]
2.2 对于javaBean,Map : JSONObject.fromObject(javaBean对象); {name1:value1,name2:value2}
对于json数据,它只有两种格式 1.[值1,值2,...] ------>这就是javascript中的数组 2.{name:value,....} ---->就是javascript中的对象。
但是这两种格式可以嵌套. [{},{},{}] {name:[],name:[]}
3.如果javaBean中有一个属性,不想生成在json中,怎样处理?
sonConfig config = new JsonConfig(); config.setExcludes(new String[] { "type" }); JSONArray.fromObject(ps, config).toString();
4.实例
public class JsonLibTest { // 将数组转换成json @Test public void fun1() { String[] st = { "aaa", "bbb", "ccc" }; String json = JSONArray.fromObject(st).toString(); System.out.println(json); // ["aaa","bbb","ccc"] } // 将List集合转换成json @Test public void fun2() { List<String> list = new ArrayList<String>(); list.add("111"); list.add("222"); list.add("333"); String json = JSONArray.fromObject(list).toString(); System.out.println(json); // ["111","222","333"] } // 将一个javaBean转换成json @Test public void fun3() { Product p = new Product(1, "电冰箱", 1800); String json = JSONObject.fromObject(p).toString(); System.out.println(json); // {"id":1,"name":"电冰箱","price":1800} } // 如果List<Product> @Test public void fun4() { List<Product> ps = new ArrayList<Product>(); ps.add(new Product(1, "洗衣机", 1800)); ps.add(new Product(2, "电视机", 3800)); ps.add(new Product(3, "空调", 5800)); JsonConfig config = new JsonConfig(); config.setExcludes(new String[] { "type" }); String json = JSONArray.fromObject(ps, config).toString(); System.out.println(json); } // map集合转换成json @Test public void fun5() { Map<String, String> map = new HashMap<String, String>(); map.put("aaa", "1111"); map.put("bbb", "222"); System.out.println(JSONObject.fromObject(map).toString()); } // 将json转换成java @Test public void fun6() { Product p = new Product(1, "电冰箱", 1800); JSONObject jsonObj = JSONObject.fromObject(p); // 将jsonObj在转换成java对象 Product pp= (Product) JSONObject.toBean(jsonObj,Product.class); System.out.println(pp); } }
六、Ajax操作中服务器端返回xml处理
XMHttpRequest.resposneXML;----->得到的是一个Document对象.
操作:可以自己将xml文件中的内容取出来,写回到浏览器端。也可以请求转发到一个xml文件,将这个文件信息写回到浏览器端.
注意response.setContextType("text/xml;charset=utf-8");
问题:如果没有xml文件,我们的数据是从数据库查找到,想要将其以xml格式返回怎样处理?可以使用xml插件处理 xstream,它可以在java对象与xml之间做转换.
xstream使用:
1.导包 2个.
2.将java对象转换成xml
XStream xs=new XStream(); String xml=xs.toXML(java对象);
问题:生成的xml中的名称是类的全名?
两种方式: 1.编码实现 xs.alias("person", Person.class); 2.使用注解(Annotation) @XStreamAlias(别名) 对类和变量设置别名 @XStreamAsAttribute 设置变量生成属性 @XStreamOmitField 设置变量 不生成到XML @XStreamImplicit(itemFieldName = “hobbies”) 设置集合类型变量 别名 使注解生效 xStream.autodetectAnnotations(true);
实例:1.创建ajax.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>ajax开发---xml返回</title> <script type="text/javascript" src="${pageContext.request.contextPath}/my.js"></script> <script type="text/javascript"> window.onload = function() { //得到id=t的文本框 var btn = document.getElementById("btn"); btn.onclick = function() { //第一步:得到XMLHttpRequest对象. var xmlhttp = getXmlHttpRequest(); //2.设置回调函数 xmlhttp.onreadystatechange = function() { //5.处理响应数据 当信息全部返回,并且是成功 if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { var xml = xmlhttp.responseXML; var div=document.getElementById("content"); var persons=xml.getElementsByTagName("person"); for(var i=0;i<persons.length;i++){ var id=persons[i].getElementsByTagName("id")[0].innerHTML; var name=persons[i].getElementsByTagName("name")[0].innerHTML; var age=persons[i].getElementsByTagName("age")[0].innerHTML; div.innerHTML+="id:"+id+" name:"+name+" age:"+age+"<br>"; } } }; //post请求方式,参数设置 xmlhttp.open("GET", "${pageContext.request.contextPath}/ajax7"); xmlhttp.send(null); }; }; </script> </head> <body> <input type="button" value="接收xml" id="btn"> <div id="content"> </div> </body> </html>
2.创建AjaxServlet
public class Ajax7Servlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/xml;charset=utf-8"); List<Person> ps = new ArrayList<Person>(); ps.add(new Person(1, "tom", 20)); ps.add(new Person(2, "fox", 30)); XStream xs = new XStream(); xs.autodetectAnnotations(true); String xml = xs.toXML(ps); response.getWriter().write(xml); response.getWriter().close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
Ajax的实例:
两个实体类:Province.java
@XStreamAlias("province") public class Province { private String name; @XStreamImplicit private List<City> citys; public String getName() { return name; } public void setName(String name) { this.name = name; } public List<City> getCitys() { return citys; } public void setCitys(List<City> citys) { this.citys = citys; } }
City.java
@XStreamAlias("city") public class City { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
省市级联动 XML方式
Ajax.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>ajax开发---xml返回</title> <script type="text/javascript" src="${pageContext.request.contextPath}/my.js"></script> <script type="text/javascript"> var xml; //声明全局,因为要在多个函数中使用. window.onload = function() { //得到id=t的文本框 //第一步:得到XMLHttpRequest对象. var xmlhttp = getXmlHttpRequest(); //2.设置回调函数 xmlhttp.onreadystatechange = function() { //5.处理响应数据 当信息全部返回,并且是成功 if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { xml = xmlhttp.responseXML; //得到的数据将province中信息添加 //得到xml是一个Document对象,它代表的是服务器端返回的xml. //将xml中所有province的name子元素中的文本获取到. var ps = xml.getElementsByTagName("province"); for ( var i = 0; i < ps.length; i++) { //得到每一个province元素下的第一个name子元素 var nameElement = ps[i].getElementsByTagName("name")[0]; //得到name元素中的文本信息,就是省份名称 var pname = nameElement.firstChild.nodeValue; //创建option标签,将其添加到省份下拉框中. var option = document.createElement("option"); option.text = pname; //将创建的option添加到省份下拉框中 document.getElementById("province").add(option); } } }; //post请求方式,参数设置 xmlhttp.open("GET", "${pageContext.request.contextPath}/ajax1"); xmlhttp.send(null); }; //创建一个函数,用于向城市下拉框中添加值. function fillCity() { var province=document.getElementById("province");//省份下拉框 var city=document.getElementById("city");//城市下拉框. //每一次向城市中添加信息时,将信息重置。 city.innerHTML="<option>--请选择城市--</option>"; //1.得到选中的省份名称. var pname=province.options[province.selectedIndex].text; var ps = xml.getElementsByTagName("province"); for ( var i = 0; i < ps.length; i++) { //得到每一个province元素下的第一个name子元素 var nameElement = ps[i].getElementsByTagName("name")[0]; //得到name元素中的文本信息,就是省份名称 var pElementName = (nameElement.firstChild.nodeValue); if(pname==pElementName){ //判断选择的省份名称与xml文件中的省份名称一致. var citys=ps[i].getElementsByTagName("city"); //得到所有省份的城市 for(var j=0;j<citys.length;j++){ //得到所有的城市名称 var cname=citys[j].getElementsByTagName("name")[0].firstChild.nodeValue; //创建option添加到城市下拉框中 var option = document.createElement("option"); option.text = cname; city.add(option); } } } } </script> </head> <body> <select id="province" onchange="fillCity()"> <option>--请选择省份--</option> </select> <select id="city"> <option>--请选择城市--</option> </select> </body> </html>
AjaxServlet.java
public class AjaxServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/xml;charset=utf-8"); // 1.得到数据 List<Province> ps = new ArrayList<Province>(); Province p1 = new Province(); p1.setName("黑龙江"); List<City> citys1 = new ArrayList<City>(); City city1 = new City(); city1.setName("哈尔滨"); City city11 = new City(); city11.setName("齐齐哈尔"); City city111 = new City(); city111.setName("大庆"); citys1.add(city1); citys1.add(city11); citys1.add(city111); p1.setCitys(citys1); Province p2 = new Province(); p2.setName("吉林"); List<City> citys2 = new ArrayList<City>(); City city2 = new City(); city2.setName("长春"); City city22 = new City(); city22.setName("吉林"); City city222 = new City(); city222.setName("四平"); citys2.add(city2); citys2.add(city22); citys2.add(city222); p2.setCitys(citys2); ps.add(p1); ps.add(p2); // 将ps转换成xml XStream xs = new XStream(); xs.autodetectAnnotations(true); String xml = xs.toXML(ps); response.getWriter().write(xml); response.getWriter().close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
省市级联动 Json方式
Ajax.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>ajax开发---json返回</title> <script type="text/javascript" src="${pageContext.request.contextPath}/my.js"></script> <script type="text/javascript"> var jsonObj; //声明全局,因为要在多个函数中使用. window.onload = function() { var province = document.getElementById("province");//省份下拉框 //第一步:得到XMLHttpRequest对象. var xmlhttp = getXmlHttpRequest(); //2.设置回调函数 xmlhttp.onreadystatechange = function() { //5.处理响应数据 当信息全部返回,并且是成功 if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { jsonObj = eval("(" + xmlhttp.responseText + ")"); //得到省份名称 for ( var i = 0; i < jsonObj.length; i++) { var pname = jsonObj[i].name; var option = document.createElement("option"); option.text = pname; province.add(option); } } }; //post请求方式,参数设置 xmlhttp.open("GET", "${pageContext.request.contextPath}/ajax2"); xmlhttp.send(null); }; //创建一个函数,用于向城市下拉框中添加值. function fillCity() { var province = document.getElementById("province");//省份下拉框 var city = document.getElementById("city");//城市下拉框. //每一次向城市中添加信息时,将信息重置。 city.innerHTML = "<option>--请选择城市--</option>"; var pname = province.options[province.selectedIndex].text; for ( var i = 0; i < jsonObj.length; i++) { var pElementName = jsonObj[i].name; if (pname == pElementName) { var citys = jsonObj[i].citys; for ( var j = 0; j < citys.length; j++) { var cname = citys[j].name; var option = document.createElement("option"); option.text = cname; city.add(option); } } } } </script> </head> <body> <select id="province" onchange="fillCity()"> <option>--请选择省份--</option> </select> <select id="city"> <option>--请选择城市--</option> </select> </body> </html>
AjaxServlet.java
public class AjaxServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/xml;charset=utf-8"); // 1.得到数据 List<Province> ps = new ArrayList<Province>(); Province p1 = new Province(); p1.setName("黑龙江"); List<City> citys1 = new ArrayList<City>(); City city1 = new City(); city1.setName("哈尔滨"); City city11 = new City(); city11.setName("齐齐哈尔"); City city111 = new City(); city111.setName("大庆"); citys1.add(city1); citys1.add(city11); citys1.add(city111); p1.setCitys(citys1); Province p2 = new Province(); p2.setName("吉林"); List<City> citys2 = new ArrayList<City>(); City city2 = new City(); city2.setName("长春"); City city22 = new City(); city22.setName("吉林"); City city222 = new City(); city222.setName("四平"); citys2.add(city2); citys2.add(city22); citys2.add(city222); p2.setCitys(citys2); ps.add(p1); ps.add(p2); // 转换成json String json = JSONArray.fromObject(ps).toString(); response.getWriter().write(json); response.getWriter().close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }