一、注册案例(Get方式)
1、前台
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>ajax</title> </head> <body> <form> 用户名[GET]:<input id="usernameID" type="text" name="username" /> 光标移出后,立即检查结果 </form> <hr /> <span id="resultID"></span> <script type="text/javascript"> //定位文本框,同时提供焦点失去事件 document.getElementById("usernameID").onblur = function() { var userName=this.value; //判断是否为空 if(userName.length==0){ document.getElementById("resultID").innerHTML="<font color='red'>用户名必填</font>"; }else{ //对汉字进行UTF-8编码 userName=encodeURI(userName); console.log(userName); //1、创建AJAX对象 var ajax = createAJAX(); //2、准备发送请求 var method = "GET"; //为了适应IE浏览器对其不变的地址缓存,以致其不会继续去发送请求,所以加上时间,保证唯一 var url = "${pageContext.request.contextPath}/RegisterServlet?time="+new Date().getTime()+"&userName="+userName; ajax.open(method, url); //3、真正发送请求的具体数据到服务器,如果球体中无数据,就用null表示 ajax.send(null); //4、Ajax异步对象不断监听服务器 ajax.onreadystatechange = function() { //如果状态码为4 if (ajax.readyState == 4) { //如果响应码为200 if (ajax.status == 200) { var tip=ajax.responseText; document.getElementById("resultID").innerHTML = tip; } } } } } function createAJAX() { var ajax = null; try { //如果是IE5——IE12的话 ajax = new ActiveXObject("microsoft.xmlhttp"); } catch (e1) { //如果是非IE的话 ajax = new XMLHttpRequest(); } return ajax; } </script> </body> </html>
2、servlet
public class RegisterServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userName = request.getParameter("userName"); userName=new String(userName.getBytes("iso-8859-1"),"utf-8"); String tip = "<font color='green'>可以注册</font>"; if("郭庆兴".equals(userName)){ tip = "<font color='red'>该用户已存在</font>"; } response.setContentType("text/html;charset=UTF-8"); PrintWriter pw = response.getWriter(); pw.write(tip); pw.flush(); pw.close(); } }
二、注册(POST)
1、前台
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>ajax</title> </head> <body> <form> 用户名[POST]:<input id="usernameID" type="text" name="username" /> 光标移出后,立即检查结果 </form> <hr/> <span id="resultID"></span> <script type="text/javascript"> //定位文本框,同时提供焦点失去事件 document.getElementById("usernameID").onblur = function() { var userName=this.value; //判断是否为空 if(userName.length==0){ document.getElementById("resultID").innerHTML="<font color='red'>用户名必填</font>"; }else{ //1、创建AJAX对象 var ajax = createAJAX(); //2、准备发送请求 var method = "POST"; //为了适应IE浏览器对其不变的地址缓存,以致其不会继续去发送请求,所以加上时间,保证唯一 var url = "${pageContext.request.contextPath}/RegisterServlet?time="+new Date().getTime(); ajax.open(method, url); //设置AJAX请求头为POST,他会将请求体中的汉字自动进行UTF-8的编码 //<form action="" enctype="application/x-www-form-urlencoded"></form> ajax.setRequestHeader("content-type","application/x-www-form-urlencoded"); //3、真正发送请求的具体数据到服务器, var content="userName="+userName; ajax.send(content); //4、Ajax异步对象不断监听服务器 ajax.onreadystatechange = function() { //如果状态码为4 if (ajax.readyState == 4) { //如果响应码为200 if (ajax.status == 200) { var tip=ajax.responseText; //创建img标签 var imgElement=document.createElement("img"); //设置imng标签的属性 imgElement.src=tip; imgElement.style.width="12px"; imgElement.style.height="12px"; //定位span标签、 var spanElement=document.getElementById("resultID"); //清空span标签 spanElement.innerHTML = ""; //请img标签加入到span标签中去 spanElement.appendChild(imgElement); } } } } } function createAJAX() { var ajax = null; try { //如果是IE5——IE12的话 ajax = new ActiveXObject("microsoft.xmlhttp"); } catch (e1) { //如果是非IE的话 ajax = new XMLHttpRequest(); } return ajax; } </script> </body> </html>
这与前面,有个地方不同,就是在open方法和send方法之间要设置一个响应头,否则后台没办法接收到数据。
2、后台servlet
public class RegisterServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); String userName=request.getParameter("userName"); String tip="img/right.gif"; if ("郭庆兴".equals(userName)) { tip="img/error.gif"; } response.setContentType("text/html;charset=utf-8"); PrintWriter pw=response.getWriter(); pw.write(tip); pw.flush(); pw.close(); } }
结果如图
三、三级联动
省份-城市联动
1、前台
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>ajax</title> </head> <body> 省份:<select id="provinceID" style="width: 120px"> <option>选择省份</option> <option>湖北省</option> <option>广东省</option> <option>湖南省</option> </select> 城市:<select id="cityID" style="width: 120px"> <option>选择城市</option> </select> <script type="text/javascript"> //定位下拉框,同时添加内容改变事件 document.getElementById("provinceID").onchange = function() { //清空城市下拉列表的内容,除了第一项 var cityElement=document.getElementById("cityID"); cityElement.length=1; //获取选中的省份标签的索引号,从0开始 var index=this.selectedIndex; //定位当前的option标签 var optionElement=this[index]; //获取option内容的标签 var province=optionElement.innerHTML; //如果选中的不是提示“选择省份”,不需要向服务器去查询城市信息 if ("选择省份" != province) { var ajax=createAJAX(); var method="post"; var url="${pageContext.request.contextPath}/ProvinceServlet?time="+new Date().getTime(); ajax.open(method, url); //设置响应头 ajax.setRequestHeader("content-type", "application/x-www-form-urlencoded"); var content="province="+province; ajax.send(content); //***************等待服务器发送数据************** ajax.onreadystatechange=function(){ if (ajax.readyState==4) { if (ajax.status=200) { //从ajax异步对象中获取服务器响应的xml文档 var xmlDocument = ajax.responseXML; //按照DOM规则解析xml文档 var cityElementArray = xmlDocument.getElementsByTagName("city"); var size=cityElementArray.length; for (var i = 0; i < size; i++) { var city = cityElementArray[i].firstChild.nodeValue; //开始往城市的下拉栏添加 var optionElement=document.createElement("option"); optionElement.innerHTML=city; cityElement.appendChild(optionElement); } } } } } } function createAJAX() { var ajax = null; try { //如果是IE5——IE12的话 ajax = new ActiveXObject("microsoft.xmlhttp"); } catch (e1) { //如果是非IE的话 ajax = new XMLHttpRequest(); } return ajax; } </script> </body>
2、后台servlet
package com.gqx.test1; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 二级联动,基于xml方式完成 * @author 郭庆兴 * */ public class ProvinceServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String province=request.getParameter("province"); //通知ajax异步对象,服务器响应的数据格式为xml response.setContentType("text/xml;charset=UTF-8"); //获取字符流输出 PrintWriter pw=response.getWriter(); //如果是连接数据库的话,应该查出来的是一个list集合,然后将其按xml的方式封装,如下格式 pw.write("<?xml version='1.0' encoding='UTF-8'?>"); pw.write("<root>"); if ("湖北省".equals(province)) { pw.write("<city>武汉</city>"); pw.write("<city>黄石</city>"); pw.write("<city>荆州</city>"); pw.write("<city>襄阳</city>"); pw.write("<city>宜昌</city>"); }else if ("湖南省".equals(province)) { pw.write("<city>长沙</city>"); pw.write("<city>株洲</city>"); pw.write("<city>萍乡</city>"); pw.write("<city>湘潭</city>"); pw.write("<city>岳阳</city>"); }else if ("广东省".equals(province)) { pw.write("<city>广州</city>"); pw.write("<city>深圳</city>"); pw.write("<city>中山</city>"); pw.write("<city>佛山</city>"); pw.write("<city>汕头</city>"); pw.write("<city>珠海</city>"); } pw.write("</root>"); pw.flush(); pw.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
这里要注意的是在后台要用xml的方式去发送数据,同时前台去接受数据的时候要去解析,先接受
//从ajax异步对象中获取服务器响应的xml文档 var xmlDocument = ajax.responseXML; //按照DOM规则解析xml文档 var cityElementArray = xmlDocument.getElementsByTagName("city");
要获取xml最小节点内的数据可以通过如下方法去获取
var city = cityElementArray[i].firstChild.nodeValue;
最终 效果如下