使用Ajax完成验证

前端之家收集整理的这篇文章主要介绍了使用Ajax完成验证前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

在看书的同时,写的小例子都想把他给保存下来,供以后复习用。

一个日期验证的例子,也许不完美,但是逻辑还是比较清晰的:

1.validation.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>用户验证</title>
<script type="text/javascript">
		var xmlHttp;
		function createXHR()
		{
			if(window.ActiveXObject)
			{
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			}else if(window.XMLHttpRequest)
			{
				xmlHttp = new XMLHttpRequest();
			}
		}		
		function setMessage (message,isValid)
		{
			var messageArea = document.getElementById("dateMessage");
			var fontColor = "red";
			if(isValid=="true")
			{
				fontColor = "green";
			}			
			messageArea.innerHTML="<font color="+fontColor+">"+message+"</font>";
		}		
		function callBack()
		{
			if(xmlHttp.readyState==4)
			{
				if(xmlHttp.status==200)
				{
					var mes = xmlHttp.responseXML.getElementsByTagName("message")[0].firstChild.data ;
					var val = xmlHttp.responseXML.getElementsByTagName("passed")[0].firstChild.data ;
					setMessage(mes,val);
				}
			}
		}
		
		function validate()
		{
			createXHR();
			var date = document.getElementById("birthDate");
			var url = "ValidationServlet?";
			url=url+"birthDate="+escape(date.value);
			xmlHttp.onreadystatechange=callBack;
			xmlHttp.open("GET",url,true);			
			xmlHttp.send(null);
		}
</script>
</head>
<body style="background-color:#ffccff">
	<h1>Ajax Validation Example</h1>
	Birth Date :<input type="text" size="10" id="birthDate" onchage="validate()">
	<input type="button" onclick="validate()"/>
	<div id="dateMessage"></div>
</body>
</html>


2.ValidationServlet.java

package com.wch.ajax.servlet;

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import javax.servlet.*;
import javax.servlet.http.*;

public class ValidationServlet extends HttpServlet {    
    
    /** Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request,HttpServletResponse response)
    throws ServletException,IOException {
        PrintWriter out = response.getWriter();
        
        boolean passed = validateDate(request.getParameter("birthDate"));
        response.setContentType("text/xml");
        response.setHeader("Cache-Control","no-cache");
        String message = "You have entered an invalid date.";
        
        if (passed) {
            message = "You have entered a valid date.";
        }
        out.println("<response>");
        out.println("<passed>" + Boolean.toString(passed) + "</passed>");
        out.println("<message>" + message + "</message>");
        out.println("</response>");
        out.close();
     }
    
    /**
     * Checks to see whether the argument is a valid date.
     * A null date is considered invalid. This method
     * used the default data formatter and lenient
     * parsing.
     *
     * @param date a String representing the date to check
     * @return message a String represnting the outcome of the check
     */
    private boolean validateDate(String date) {
        
        boolean isValid = true;
        if(date != null) {
            SimpleDateFormat formatter= new SimpleDateFormat("MM/dd/yyyy");
            try {
                formatter.parse(date); 
            } catch (ParseException pe) {
                System.out.println(pe.toString());
                isValid = false;
            }
        } else {
            isValid = false;
        }
        return isValid;
    }
}



3.web.xml


<servlet>
    <servlet-name>ValidationServlet</servlet-name>
    <servlet-class>com.wch.ajax.servlet.ValidationServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ValidationServlet</servlet-name>
    <url-pattern>/ValidationServlet</url-pattern>
  </servlet-mapping>

4.运行结果:

原文链接:https://www.f2er.com/ajax/166622.html

猜你在找的Ajax相关文章