@H_301_8@
@H_301_8@<%@ page language="java" pageEncoding="utf-8"%> <script type="text/javascript" language="javascript"> //根据不同的浏览器创建不同的XMLHttpRequest对象 function createXmlHttpRequest() { var xmlreq = false; if (window.XMLHttpRequest) { xmlreq = new XMLHttpRequest(); } else if (window.ActiveXObject) { try { //创建较新版本的对象 xmlreq = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e1) { try { xmlreq = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e2) { } } } return xmlreq; } function userNameCheck() { var username = document.all.username.value;//获得text的值 var request = createXmlHttpRequest();//创建request 对象 request.open("post","ValidationServlet?username="+username);//建立到服务器的新请求 request.send();//向服务器发送请求 request.onreadystatechange=function()//指定当readyState属性改变时的事件处理句柄 { if (request.readyState==4)//提取当前HTTP的就绪状态,状态4表示:响应已完成,可以访问服务器响应并使用它 if (request.status==200)//HTTP状态,我们期望的状态码是 200,它表示一切顺利。 //如果就绪状态是 4 而且状态码是 200,就可以处理服务器的数据了,而且这些数据应该就是要求的数据 { var value = request.responseText;//服务器返回响应文本 if (value=="true") { document.all.unc.innerHTML="该用户名已存在"; } else { document.all.unc.innerHTML="该用户名可以注册"; } } } } </script> <html> <head> <title>AjaxTest</title> </head> <body> 用户姓名: <input type="text" name="username" onblur="userNameCheck()"/><font color="red" size="-1" id="unc"></font> </body> </html> @H_301_8@ValidationServlet.java:
package sample; import java.io.*; import java.text.*; import javax.servlet.*; import javax.servlet.http.*; public class ValidationServlet extends HttpServlet { protected void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException { this.doPost(request,response); } protected void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException { String username=request.getParameter("username"); if(username.equals("lixin")) response.getWriter().print("true"); else response.getWriter().print("false"); }} @H_301_8@