<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" >
<html> <head> <title>Using Ajax for validation</title> <script type="text/javascript">
var xmlHttp;
function createXMLHttpRequest() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}else if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
}
function validate() {
createXMLHttpRequest();
var date = document.getElementByIdx_x("birthDate");
var url = "Handler.ashx?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_r("message")[0].firstChild.data;
var val =xmlHttp.responseXML.getElementsByTagName_r("passed")[0].firstChild.data;
setMessage(mes, val);
}
}
}
function setMessage(message, isValid) {
var messageArea = document.getElementByIdx_x("dateMessage");
var fontColor = "red";
if (isValid) {
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" onchange="validate();"/> <div id="dateMessage"></div> </body>
</html>
服务端代码
<%@ WebHandler Language="C#" class="Handler" %>
using System;
using System.Web;
using System.Text;
using System.Collections;
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
bool pass = Validate(context.Request.QueryString["birthDate"]);
context.Response.ContentType = "text/xml";
context.Response.AddHeader("Cache-Control","no-cache");
String message = "您输入的日期不正确.";
if (pass)
{
message = "您输入的日期正确.";
}
context.Response.Write("<response>");
context.Response.Write("<passed>"+pass+"</passed>");
context.Response.Write("<message>" + message + "</message>");
context.Response.Write("</response>");
context.Response.End();
}
public bool Validate(string date)
{
bool isValid = true;
if (date != null)
{
try
{
DateTime.Parse(date);
}
catch (Exception)
{
isValid = false;
}
}
else
{
isValid = false;
}
return isValid;
}
public bool IsReusable {
get {
return false;
}
}
}