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

Ajax简单示例

声明:本文示例代码来自 Brett McLaughlin 关于Ajax的系列文章,是对原文代码片段的总结和再次实现,如果你是ajax新手的话,强烈推荐拜读其文——?https://www.ibm.com/developerworks/cn/web/wa-ajaxintro/

?

示例说明:

填写City和State,异步获取Zip Code,此处Zip Code和State相同。

?

ajax1.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 demo</title>
<script type="text/javascript">
	/* Create a new XMLHttpRequest object to talk to the Web server */
	var xmlHttp = false;
	try {
		xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try {
			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (e2) {
			xmlHttp = false;
		}
	}
	if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
		xmlHttp = new XMLHttpRequest();
	}

	function callServer() {
		// Get the city and state from the web form
		var city = document.getElementById("city").value;
		var state = document.getElementById("state").value;
		// Only go on if there are values for both fields
		if ((city == null) || (city == ""))
			return;
		if ((state == null) || (state == ""))
			return;
		// Build the URL to connect to
		var url = "ajaxDemo?city=" + escape(city) + "&state=" + escape(state);
		// Open a connection to the server
		xmlHttp.open("GET", url, true);
		// Setup a function for the server to run when it's done
		xmlHttp.onreadystatechange = updatePage;
		// Send the request
		xmlHttp.send(null);
	}

	function updatePage() {
		if (xmlHttp.readyState == 4) {
			if (xmlHttp.status == 200) {
				var response = xmlHttp.responseText;
				document.getElementById("zipCode").value = response;
			} else if (xmlHttp.status = 404) {
				alert("Request URL does not exit!");
			} else {
				alert("Error : status code is " + xmlHttp.status);
			}
		}
	}
</script>
</head>
<body>
<div align="center">
<form>
<table>
	<tr>
		<td>City: &nbsp;</td>
		<td align="left"><input type="text" name="city" id="city"
			size="25" onchange="callServer();" /></td>
	</tr>
	<tr>
		<td>State:&nbsp;</td>
		<td align="left"><input type="text" name="state" id="state"
			size="25" onChange="callServer();" /></td>
	</tr>
	<tr>
		<td>Zip Code:&nbsp;</td>
		<td align="left"><input type="text" name="zipCode" id="zipCode"
			size="5" /></td>
	</tr>
</table>
</form>
</div>
</body>
</html>

?

AjaxDemoServlet.java

package org.zzh.ajaxdemo.servlet;

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;

/**
 * Servlet implementation class AjaxDemoServlet
 */
public class AjaxDemoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AjaxDemoServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	private void processRequest(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		res.setContentType("text/html"