DOM方式实现验证
<!DOCTYPE html><html><head><meta charset=\"UTF-8\"><title>Insert title here</title><script type=\"text/javascript\" src=\"/ajax/JS/my.js\"></script><script type=\"text/javascript\">function checkUsername(){var usernameValue=document.getElementById(\"username\").value;var xmlHttp = getXmlHttpRequest();xmlHttp.onreadystatechange = function() {if (xmlHttp.readyState == 4) {if (xmlHttp.status == 200) {//根据服务器响应情况来处理响应数据var responseMsg = xmlHttp.responseText;//处理服务器响应的数据,在span块中显示信息document.getElementById(\"username_msg\").innerHTML = responseMsg;}}};xmlHttp.open(\"POST\", \"/ajax/userServlet\");//发送请求xmlHttp.setRequestHeader(\"content-type\",\"application/x-www-form-urlencoded\");xmlHttp.send(\"username=\" + usernameValue);}</script></head><body><input type=\"text\" id=\"username\" onblur=\"checkUsername()\"><span id=\"username_msg\"></span></body></html>
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String username=request.getParameter(\"username\");String msg=\"\";if(\"tom\".equals(username)) {msg=\"<font color=\'red\'>用户名被占用</font>\";}else {msg=\"<font color=\'green\'>用户名可以使用</font>\";}response.setCharacterEncoding(\"utf-8\");response.getWriter().write(msg);}
jQuery-ajax方式
<!DOCTYPE html><html><head><meta charset=\"UTF-8\"><title>Insert title here</title><script type=\"text/javascript\" src=\"/jquery_ajax/js/jquery-1.8.3.js\"></script><script type=\"text/javascript\">//页面加载完成后$(function() {//添加失焦事件$(\"#username\").blur(function() {//获取录入的用户名var usernamevalue = $(\"#username\").val();//向服务器发送请求var url=\"/jquery_ajax/load\";//$.get请求$.get(url,{\"username\":usernamevalue},function(data){$(\"#username_span\").html(data);},\"html\");});});</script></head><body><input type=\"text\" name=\"username\" id=\"username\"><span id=\"username_span\"></span><br><input type=\"password\" name=\"password\"><br></body></html>
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// 解决乱码request.setCharacterEncoding(\"utf-8\");response.setCharacterEncoding(\"utf-8\");// 1.得到用户名String username = request.getParameter(\"username\");// 2.判断用户名是否可以使用if (\"tom\".equals(username)) {// 用户名不可以使用response.getWriter().write(\"<font color=\'red\'>用户名被占用</font>\");} else {// 用户名可以使用response.getWriter().write(\"<font color=\'green\'>用户名可以使用</font>\");}}
对比可以看出,jQuery提供的get或post方法要比原始的ajax请求的方法简便得多,更容易使用。