用ajax做简单的数据验证

     这几天把ajax前面的基础大概了解了下,基本知道了ajax的原理。

     下午继续在看书,做了个日期数据验证的小例子。

页面validation.html代码


<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" >
<% @ page contentType="text/html;charset=GBK"  %>
< html >
  
< head >
    
< title > validation.html </ title >    
 
< script  type ="text/javascript" >
  
var xmlHttp;
  
  
function createXMLHttpRequest(){
 
   
if(window.ActiveXObject){
    xmlHttp 
= new ActiveXObject("Microsoft.XMLHTTP");
   }
else{
    xmlHttp 
= new XMLHttpRequest;
   }

     }
  
  
  
function validate(){
   createXMLHttpRequest();
   
var date = document.getElementById("birthDay");
   
var url = "/ajaxTest/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.nodeValue;
     
var val = xmlHttp.responseXML.getElementsByTagName("passed")[0].firstChild.nodeValue;
     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 >
 
 Birthday: 
< input  type ="text"  id ="birthDay"   onChange ="validate();" >< div  id ="dateMessage" ></ div >

 
  
</ body >
</ html >

 

servlet 代码ValidationServlet.java

 

package  org.jason.servlet;

import  java.io.IOException;
import  java.io.PrintWriter;
import  java.text.ParseException;
import  java.text.SimpleDateFormat;

import  javax.servlet.ServletException;
import  javax.servlet.http.HttpServlet;
import  javax.servlet.http.HttpServletRequest;
import  javax.servlet.http.HttpServletResponse;

public   class  ValidationServlet  extends  HttpServlet  {

    
/**
     * Constructor of the object.
     
*/

    
public ValidationServlet() {
        
super();
    }


    
/**
     * Destruction of the servlet. <br>
     
*/

    
public void destroy() {
        
super.destroy(); // Just puts "destroy" string in log
        
// Put your code here
    }


    
/**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * 
@param request the request send by the client to the server
     * 
@param response the response send by the server to the client
     * 
@throws ServletException if an error occurred
     * 
@throws IOException if an error occurred
     
*/

    
public void doGet(HttpServletRequest request, HttpServletResponse response)
            
throws ServletException, IOException {

        response.setContentType(
"text/xml;charset=GBK");
        PrintWriter out 
= response.getWriter();
        
        
boolean passed = validateDate(request.getParameter("birthDate"));
        
        response.setHeader(
"Cache-Control","no-cache");
        
        String message 
= "日期格式错误 请按(YYYY/MM/DD)输入";
        
if(passed){
            
            message 
= "输入格式正确";
        }

        out.println(
"<?xml version='1.0' encoding='GBK'?>");
        out.println(
"<response>");
        out.println(
"<passed>" + Boolean.toString(passed) + "</passed>");
        out.println(
"<message>" + message + "</message>");
        out.println(
"</response>");

        out.flush();
        out.close();
    }


    
/**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * 
@param request the request send by the client to the server
     * 
@param response the response send by the server to the client
     * 
@throws ServletException if an error occurred
     * 
@throws IOException if an error occurred
     
*/

    
public void doPost(HttpServletRequest request, HttpServletResponse response)
            
throws ServletException, IOException {

            doGet(request,response);
    }


    
/**
     * Initialization of the servlet. <br>
     *
     * 
@throws ServletException if an error occure
     
*/

    
public void init() throws ServletException {
        
// Put your code here
    }

    
    
    
protected boolean validateDate(String date){
        
boolean isValid = true;
        
if(date!=null){
            
            SimpleDateFormat formatter 
= new SimpleDateFormat("MM/dd/yyyy");
            
try {
                formatter.parse(date);
            }
 catch (ParseException e) {
                
// TODO Auto-generated catch block
                e.printStackTrace();
                isValid 
= false;
            }

        }
else{
            
            isValid 
= false;
        }

        
return isValid;
    }

    

}

 

       在这里面遇到一个问题,那就是返回来的 responseText 或 responseXML 的值中含有中文就变乱码。

一开始只设置了response.setContentType("text/xml");

      即使在下面设置out.println("<?xml version='1.0' encoding='GBK'?>"); 也不能解决中文乱码问题。

     最后在网上找到一定要设置成response.setContentType("text/xml;charset=GBK");才能解决。。

     看着问号变中文,就是那回事

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值