文件结构:
Ajax.js
var req; function zz(){ alert("hello"); } function validate() { //获取表单提交的内容 var idField = document.getElementById("userName"); //访问validate.do这个servlet,同时把获取的表单内容idField加入url字符串,以便传递给validate.do var url = "validate.do?id=" + escape(idField.value); //创建一个XMLHttpRequest对象req if(window.XMLHttpRequest) { //IE7, Firefox, Opera支持 req = new XMLHttpRequest(); }else if(window.ActiveXObject) { //IE5,IE6支持 req = new ActiveXObject("Microsoft.XMLHTTP"); } /* open(String method,String url, boolean )函数有3个参数 method参数指定向servlet发送请求所使用的方法,有GET,POST等 boolean值指定是否异步,true为使用,false为不使用。 我们使用异步才能体会到Ajax强大的异步功能。 */ req.open("GET", url, true); //onreadystatechange属性存有处理服务器响应的函数,有5个取值分别代表不同状态 req.onreadystatechange = callback; //send函数发送请求 req.send(null); } function callback() { if(req.readyState == 4 && req.status == 200) { var check = req.responseText; show (check); } } function show(str) { if(str == "OK") { var show = "<font color='green'>恭喜!!用户名可用!</font>"; document.getElementById("info").innerHTML = show; } else if( str == "NO") { var show = "<font color='red'>对不起,用户名不可用!!请重新输入!</font>"; document.getElementById("info").innerHTML = show; } }
<%@page contentType="text/html" pageEncoding="gb2312"%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <script type="text/javascript" src="Ajax.js"></script> </head> <body> <h1>Test Ajax</h1><p> <form action="" method="get" name="form"> <br> 输入用户名: <input type="text" size="10" maxlength="8" id="userName" name="name" onblur="validate()"> <span id="info"></span> <br> 输入商品名: <input type="text" size="10" maxlength="8" > </form> <input type="button" onclick="zz()" /> </body> </html>
package com.zxl; 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; public class DoAjaxServlet extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=gb2312"); PrintWriter out = response.getWriter(); try { response.setContentType("text/html"); response.setHeader("Cache-Control", "no-store"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); String name = request.getParameter("id"); if(name.equals("1")) { out.write("OK"); } else { out.write("NO"); } } finally { out.close(); } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override public String getServletInfo() { return "Short description"; } }