当前位置: 代码迷 >> Ajax >> Ajax简略示例
  详细解决方案

Ajax简略示例

热度:314   发布时间:2012-08-28 12:37:01.0
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");
		PrintWriter out = res.getWriter();
		String city = req.getParameter("city");
		String state = req.getParameter("state");
		
		if("nanjing".equals(city)) {
			out.println(state);
		} else {
			out.println(state);
		}
		out.close();
	}
}

??

?

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>AjaxDemo</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description></description>
    <display-name>AjaxDemoServlet</display-name>
    <servlet-name>AjaxDemoServlet</servlet-name>
    <servlet-class>org.zzh.ajaxdemo.servlet.AjaxDemoServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>AjaxDemoServlet</servlet-name>
    <url-pattern>/ajaxDemo</url-pattern>
  </servlet-mapping>
</web-app>

?

示例在Firefox3.6.6 和 IE8中测试正常。

  相关解决方案