日期:2014-05-16  浏览次数:20594 次

简单的AJAX例子详解

ajax.jsp

?

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>AJAX实例详解</title>
<script type="text/javascript">

	var myRequest;

    // 创建XMLHttpRequest对象
	function createXMLHttpRequest() {
		if(window.ActiveXObject) { // 浏览器是否支持ActiveX对象
			myRequest = new ActiveXObject("Microsoft.XMLHTTP");
		} else if(window.XMLHttpRequest) {
			myRequest = new XMLHttpRequest();
		}
	}
	
   // 建立发送异步数据请求的函数doAjax
	function doAjax() { 
		createXMLHttpRequest();  // 调用创建XMLHttpRequest对象的方法
		var username = document.getElementById("username").value;	// 获取文本域中的值		
		myRequest.open("get", "plain.do?username="+username, true);	// 建立对服务器的调用
		myRequest.onreadystatechange = updatePage; // 设定处理服务器响应函数
        myRequest.send(null); //用get方式建立调用,必须发送null	

	 function updatePage() {
			if(myRequest.readyState == 4) { //监视服务器端的状态改变. 用于测试响应是否已完成
				if(myRequest.status == 200) {//获得服务器的HTTP状态码. 用于判断数据请求是否成功
					var data = myRequest.responseText; // 获取服务器传递信息
					var res = document.getElementById("message");	
					res.innerHTML = data;
					alert(data); // 通过 responseText 属性来取回由服务器返回的数据
				}				
			}
		}
	}	
</script>			
</head>

<body>
<form action="">
	<table>
    	<tbody>
    		<tr>
  				<td>账号:</td>
  				<td><input name="username" type="text" id="username" onchange="doAjax();"></td> 
  			</tr>
  			<tr>
  				<td>密码:</td>
  				<td><input name="password" type="password"></td>
  			</tr>
    	</tbody>
    </table>
</form>
<p id="message">注册成功???</p>
</body>
</html>

?

PlainServlet.java

?

package com.lian.servlet;

import java.io.IOException;
import java.io.Writer;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class PlainServlet extends HttpServlet {
	
	/*
	 * 接受请求的服务器端程序
	 * 
	 */

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {		
		Writer out = resp.getWriter();
		
		String username = req.getParameter("username");
		
		if("test".equals(username)) {
			out.write("no");
		} else {
			out.write("yes");
		}	
		
	}	
}
?

web.xml相应配置

?

<servlet>
	<servlet-name>PlainServlet</servlet-name>
	<servlet-class>com.lian.servlet.PlainServlet</servlet-class>
</servlet>

<servlet-mapping>
	<servlet-name>PlainServlet</servlet-name>
	<url-pattern>/plain.do</url-pattern>
</servlet-mapping>
?

?