用Ajax完成驗證

來源:互聯網
上載者:User
ajax    商務邏輯:一個標準的輸入框,要求輸入日期格式的文本,符合要求用綠字顯示資訊,否則用紅字提示。

    頁面:Validation.html

   <%@ page contentType="text/html; charset=GBK" %>
<html>
<head>
<title>
使用ajax進行驗證
</title>
<script type="text/javascript">
 //xmlHttpRequest對象
 var xmlHttp;

        //建立xmlHttpRequest對象
        function createXMLHttpRequest(){
         if (window.ActiveXObject){
          xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
                }
                else if(window.XMLHttpRequest){
                 xmlHttp = new XMLHttpRequest();
                }
          }

          //驗證方法
          function validate(){
             //建立對象
           createXMLHttpRequest();
                //得到表單日期值
                var date = document.getElementById("birthDate");
                //提交地址
                var url = "ValidationServlet?birthDate=" + escape(date.value);
                xmlHttp.open("GET",url,true);
                xmlHttp.onreadystatechange=callback;
                xmlHttp.send(null);
          }

          //回調方法
          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 setMessage(message,isValid){
            var messageArea = document.getElementById("dateMessage");
            var fontColor = "red";
            if (isValid == "true"){
             fontColor = "green";
            }

            messageArea.innerHTML="<font color=" + fontColor + ">" + message + "</font>";
          }
</script>

</head>
<body>
<h1>
Ajax Validation Example
</h1>
Birth date:<input type="text" size="10" id="birthDate" />
<div id="dateMessage"></div>
</body>
</html>

伺服器端代碼,執行驗證

ValidationServlet.java

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.text.SimpleDateFormat;

public class ValidationServlet extends HttpServlet {
  private static final String CONTENT_TYPE = "text/html; charset=GBK";

  //Initialize global variables
  public void init() throws ServletException {
  }

  /**
   * 處理Get請求
   * @param request HttpServletRequest
   * @param response HttpServletResponse
   * @throws ServletException
   * @throws IOException
   */
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType(CONTENT_TYPE);
    //得到輸出對象
    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.";
    }

    //輸入xml格式字串
    out.println("<response>");
    out.println("<passed>" + Boolean.toString(passed) + "</passed>");
    out.println("<message>" + message + "</message>");
    out.println("</response>");
    out.close();
  }

  //Clean up resources
  public void destroy() {
  }

  /**
   * 驗證日期
   * @param date String    日期
   * @return boolean
   */
  private boolean validateDate(String date){
    boolean isValid = true;
    if (date != null){
      SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
      try {
        formatter.parse(date);
      }
      catch (Exception ex) {
        System.out.println(ex.toString());
        isValid = false;
      }
    }
    else{
      isValid = false;
    }

    return isValid;
  }
}



相關文章

Cloud Intelligence Leading the Digital Future

Alibaba Cloud ACtivate Online Conference, Nov. 20th & 21st, 2019 (UTC+08)

Register Now >

11.11 Big Sale for Cloud

Get Unbeatable Offers with up to 90% Off,Oct.24-Nov.13 (UTC+8)

Get It Now >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。