当光标移开文本框时,基于HTML,以GET或POST方式,检查注册用户名是否存在,使用DOM对象。效果如下图:
Jsp和javascript代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'checkUser.jsp' starting page</title> <script type="text/javascript" src="js/createAjax.js"></script> </head> <body> 用户名:<input type="text" name="user" id="userId"> <br> <span></span> <script type="text/javascript"> //创建ajax对象 var ajax = createAjax(); //创建鼠标失去焦点事件 document.getElementById("userId").onblur = function(){ //准备发送请求 var method = "post"; var url = "${pageContext.request.contextPath}/CheckUserServlet?id="+new Date().getTime(); ajax.open(method,url,true); /* *设置AJAX自动将请求体的中文进行编码, *在默认情况下,AJAX不会自动对请求体中文编码的 *AJAX将会以表单POST形式发送到服务器 *如果该没该句代码,AJAX不会以表单形式发送请求体数据 */ ajax.setRequestHeader("content-type","application/x-www-form-urlencoded"); //真正发送请求 username = this.value; var content = "username="+ username; ajax.send(content); //监听服务器响应 ajax.onreadystatechange = function(){ //判断响应状态和响应码 if(ajax.readyState==4){ if(ajax.status){ //接受服务器响应的字符串 var text = ajax.responseText; //将text添加到span标签内 document.getElementsByTagName("span")[0].innerHTML = text; } } }; }; </script> </body> </html>servlet代码如下:
package kerwin.ajax; 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 CheckUserServlet extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { //设置解码方式 request.setCharacterEncoding("utf-8"); response.setContentType("text/html; charset=utf-8"); //获取用户名 String username = request.getParameter("username"); //模拟调用业务层 String msg = "<font color='green'>可以注册!!</font>"; if("杰克".equals(username)){ msg = "<font color='red'>该用户名已被注册!!</font>"; } //已流IO流的方式,将普通字符串,输出到ajax引擎 response.getWriter().write(msg); } public void doPost(HttpServletRequest request,IOException { doGet(request,response); } }原文链接:https://www.f2er.com/ajax/165878.html