ajax

1、掌握AJAX 的主要作用:

2、掌握XMLHttpRequest 对象的创建及使用

XMLHttpRequest 对象

在ajax 中主要是通过XMLHttpRequest 对象处理发送异步请求和处理回应的,此对象最早 是在IE 5 中以ActiveX组件的形式出现的,一直到2005年之后才被广泛的使用,而如果要想创建一个XMLHttpRequest 对象必须使用JavaScript

在创建对象的时候一定要考虑浏览器的问题

 

<%@ page contentType="text/html" pageEncoding="GBK"%>
<html>
<head> <title>欢迎光临</title>
	<script language="javascript">
		var xmlHttp ;                           //AJAX 核心对象名称
		function createXMLHttp() {				// 创建XMLHttpRequest 核心对象
			if(window.XMLHttpRequest) {        // 判断当前使用的浏览器类型
				xmlHttp = new XMLHttpRequest();   // 表示使用的是为FireFox 内核浏览器
			} else {								// 表示使用的是IE内核的浏览器
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			}
		}
	</script>
</head>
<body>

</body>
</html>



 

 

创建对象完成之后下面就要使用此对象

 

 

下面通过一个局部刷新完成一个ajax的一个操作

ajax 必须在服务器上使用,下面建立的content.html中存在的内容要通过AJAX异步的返回到调用处

 

helloworld!

 

 

<%@ page contentType="text/html" pageEncoding="GBK"%>
<html>
<head> <title>欢迎光临</title>
	<script language="javascript">
		var xmlHttp ;                           //AJAX 核心对象名称
		function createXMLHttp() {				// 创建XMLHttpRequest 核心对象
			if(window.XMLHttpRequest) {        // 判断当前使用的浏览器类型
				xmlHttp = new XMLHttpRequest();   // 表示使用的是为其它内核浏览器
			} else {								// 表示使用的是IE内核的浏览器
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			}
		}
		function showMsg(){
			createXMLHttp() ;	//创建XMLHttp 对象 
			xmlHttp.open("POST","content.html");
			// 设置操作回调函数
			xmlHttp.onreadystatechange = showMsgCallback;
			xmlHttp.send(null);
		}
		function showMsgCallback() { //回调操作函数
			if(xmlHttp.readyState == 4) {  //调用完成
				if(xmlHttp.status == 200) {  // http状态吗正常
					var text = xmlHttp.responseText;
				document.getElementById("msg").innerHTML = text;
				}
			} 
		}
	</script>
</head>
<body>
	<input type="button" onClick="showMsg()" value="调用ajax显示内容">
	<span id="msg"></span>
</body>
</html>	

本程序完成的功能就是一个ajax 的核心功能,其中最重要的核心部分就是XMLHttpRequest 这样的一个对象的使用,把此对象掌握了,一切皆可。

 

 

ajax 异步验证

使用ajax 完成一个注册用户异步验证的功能

 

在进行一个新的用户注册之前,必须保证用户ID 不能重复,所以此处操作注意是在用户输入万新的ID 之后直接通过ajax 进行异步的验证操作

servlet

 

 

package com.demo.ajax;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CheckServlet extends HttpServlet {
	public static final String DBDRIVER = "com.mysql.jdbc.Driver";
	public static final String DBURL = "jdbc.mysql://localhost:3306/spring";
	public static final String DBUSER = "root";
	public static final String DBPASSWORD = "root";
	
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("gbk");
		resp.setContentType("text/html");
		Connection conn = null;
		PreparedStatement pstm = null;
		ResultSet rs = null;
		String userid = req.getParameter("userid");
		PrintWriter pw = resp.getWriter();
		try {
			Class.forName(DBDRIVER);
			DriverManager.getConnection(DBURL,DBUSER,DBPASSWORD);
			String sql = "select count(userid) from from user where id = ?";
			pstm = conn.prepareStatement(sql);
			
			pstm.setString(1, userid);
			rs = pstm.executeQuery();
			if(rs.next()) {
				if(rs.getInt(1) > 0) { // 用户id已经存在,不能创建
					pw.print("true");
				} else {
					pw.print("false");
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				rs.close();
				pstm.close();
				conn.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}
}

 

ajax 异步验证操作功能

 

<html>
<head> <title>欢迎光临</title>
	<script language="javascript">
		var xmlHttp;
		var flag = false;  
		function createXMLHttp() {
			if(window.XMLHttpRequest) {
				xmlHttp = new XMLHttpRequest();
			} else {
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");				
			}
		}
		function checkUserid(userid) {
			createXMLHttp();  // 以创建XMLHttpRequest 对象
			xmlHttp.open("post","CheckServlet?userid="+userid);
			xmlHttp.onreadystatechange = checkUseridCallback;
			xmlHttp.send(null);
			
			document.getElementById("msg").innerHTML = "正则验证......";
		}
		function checkUseridCallback() {

			if(xmlHttp.readyState == 4) {
				if(xmlHttp.status == 200) {
					var text = xmlHttp.responseText;
					if(text == "true") {  //用户id 已经存在
						document.getElementById("msg").innerHTML = "用户ID重复,无法使用!";
						flag = false;
					} else {
						document.getElementById("msg").innerHTML = "此用户ID可以注册!";
						flag = true;
					}
				}
			}	
		}
		function checkForm() { // 异步验证
			return flag;
		}
	</script>

</head>
<body>
<form action="regist.jsp" method="post" onsubmit="return checkForm()">
	用户ID:<input type="text" name="userid" onclick="checkUserid(this.value)"><span id="msg"></span><br/>
	姓  名: <input type="text" name="username"><br/>
	密  码: <input type="password" name="password"><br/>
	<input type="submit" value="注册">
	<input type="reset" value="重置"/>
</form>
</body>
</html>


使用ajax + xml 完成操作

 

可以直接在后台利用dom 动态生成xml文件,并交付给ajax进行显示

 

为了更好的理解关于ajax操作xml的部分,所以下面的程序先通过一个普通的静态的xml文件,来观察一些ajax、中的接收xml的返回效果。

现在已经定义了一个xml文件之后将使用ajax进行调用。

 

<?xml version="1.0" encoding="UTF-8"?>
<allarea>
	<area>
		<id>1</id>
		<title>北京</title>
	</area>
	<area>
		<id>2</id>
		<title>上海</title>
	</area>
	<area>
		<id>3</id>
		<title>广州</title>
	</area>
</allarea>

 

用dom解析,

 

<html>
<head> <title>欢迎光临</title>
	<script language="javascript">
		var xmlHttp;
		function createXMLHttp() {
			if(window.XMLHttpRequest) {
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			} else {
				xmlHttp = new XMLHttpRequest();
			}
		}
		function getCity() {
			createXMLHttp();
			xmlHttp.open("post","allarea.xml");
			xmlHttp.onreadystatechange = getCityCallback;
			xmlHttp.send(null);
		}	
		function getCityCallback() {
			 	if(xmlHttp.readyState == 4) {
			 		if(xmlHttp.status == 200) {
						var allarea = xmlHttp.responseXML.getElementsByTagName("allarea")[0].childNodes; //取得全部的allarea  下的节点
						var select = document.getElementById("city");
						select.length = 1;  //每次选择一个
						select.options[0].selected = true;  // 第一个为选中的状态
						
						for(var i=0; i<allarea.length; i++) {
							var area = allarea[i];
							var option = document.createElement("option");
							var id = area.getElementsByTagName("id")[0].firstChild.nodeValue;
							var title = area.getElementsByTagName("title")[0].firstChild.nodeValue;
							option.setAttribute("value",id);
							option.appendChild(document.createTextNode(title));
							select.appendChild(option);
						}
						alert(allarea);
			 		}
			 	}
		}
	</script>
</head>
<body onload="getCity()">
<form action="" method="post">
	请选择喜欢的城市:
	<select name="city">
		<option value="0"> - 请选择城市 - </option>
	</select>
</form>
</body>
</html>

 

 

以下代码用创建xml文档,动态解析xml文档

 

package com.demo.ajax;

import java.io.ByteArrayOutputStream;
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;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class CityServlet extends HttpServlet {
	public static final String DBDRIVER = "com.mysql.jdbc.Driver";
	public static final String DBURL = "jdbc:mysql://localhost:3306/spring";
	public static final String DBUSER = "root";
	public static final String DBPASSWORD = "root";
	
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("gbk");
		resp.setContentType("text/html");
		
		PrintWriter out = resp.getWriter();
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document document = db.newDocument();
			String data[] = {"北京","广州","上海","天津","长沙"};
			Element allarea = document.createElement("allarea");

			 for(int x=0; x<data.length; x++) {
				 Element area = document.createElement("area");
				 Element id = document.createElement("id");
				 Element title = document.createElement("title");
				 id.appendChild(document.createTextNode("" + (x+1)));
				 title.appendChild(document.createTextNode(data[x]));
				 area.appendChild(id);
				 area.appendChild(title);
				 allarea.appendChild(area);
			 }
			 document.appendChild(allarea);
			 
			 //输出
			 TransformerFactory tf = TransformerFactory.newInstance();
			 Transformer t = tf.newTransformer();
			 t.setOutputProperty(OutputKeys.ENCODING, "GBK");
			 
			 DOMSource source = new DOMSource(document);
			 StreamResult rs = new StreamResult(bos);
			 t.transform(source, rs);
			 System.out.println(bos);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

运行结果如下

<?xml version="1.0" encoding="GBK" standalone="no"?>
<allarea>
	<area>
		<id>1</id>
		<title>北京</title>
	</area>
	<area>
		<id>2</id>
		<title>广州</title>
	</area>
	<area>
		<id>3</id>
		<title>上海</title>
	</area>
	<area>
		<id>4</id>
		<title>天津</title>
	</area>
	<area>
		<id>5</id>
		<title>长沙</title>
	</area>
</allarea>

动态没有测试出来

package com.demo.ajax;

import java.io.ByteArrayOutputStream;
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;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class CityServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setContentType("text/html;charset=utf-8");
		
		PrintWriter out = resp.getWriter();
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document document = db.newDocument();
			String data[] = {"北京","广州","上海","天津","长沙"};
			Element allarea = document.createElement("allarea");
			 for(int x=0; x<data.length; x++) {
				 Element area = document.createElement("area");
				 Element id = document.createElement("id");
				 Element title = document.createElement("title");
				 id.appendChild(document.createTextNode("" + (x+1)));
				 title.appendChild(document.createTextNode(data[x]));
				 area.appendChild(id);
				 area.appendChild(title);
				 allarea.appendChild(area);
			 }
			 document.appendChild(allarea);
			 
			 //输出
			 TransformerFactory tf = TransformerFactory.newInstance();
			 Transformer t = tf.newTransformer();
			 t.setOutputProperty(OutputKeys.ENCODING, "utf-8");
			 
			 DOMSource source = new DOMSource(document);
			 StreamResult rs = new StreamResult(bos);
			 t.transform(source, rs);
			 System.out.println(bos);
			 out.println(bos);
			 out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
posted @ 2016-05-18 15:52  starskyhu  阅读(226)  评论(0编辑  收藏  举报