Ajax:数据验证
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></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.getElementById("birthDate"); var url = "WS.asmx/ValidationBirthday?birthday=" + escape(date.value); xmlHttp.onreadystatechange = handleStateChange; xmlHttp.open("GET", url, true); xmlHttp.send(null); } function handleStateChange() { 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 mssageArea = document.getElementById("dataMessage"); var fontColor = "red"; if (isValid == "true") { fontColor = "green"; } mssageArea.innerHTML = "<font color=" + fontColor + ">" + message + "</font>"; } </script> </head> <body> <h1> Ajax数据验证</h1> <form action="#"> 生日:<input type="text" size="10" id="birthDate" onchange="validate();" /> </form> <div id="dataMessage"> </div> </body> </html>
Webservice代码如下:
[WebMethod] public void ValidationBirthday() { var birthDate = validateDate(Context.Request.QueryString["birthday"]); Context.Response.ContentType = "text/xml"; string message = "输入的数据是一个非法日期"; if (birthDate) { message = "输入的数据是一个合法日期"; } Context.Response.Write("<response>"); Context.Response.Write("<passed>" + birthDate.ToString() + "</passed>"); Context.Response.Write("<message>" + message + "</message>"); Context.Response.Write("</response>"); } private bool validateDate(string date) { bool isValid = true; if (string.IsNullOrEmpty(date)) return false; DateTime dateTime = new DateTime(); if (!DateTime.TryParse(date, out dateTime)) { return false; } return isValid; }
运行效果如下: