一个基于Ajax简单的数据验证

1.新建一个checkUser.htm文件
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>无标题页</title>
    <script src="checkUser.js" type="text/javascript">
    </script>
</head>
<body>
    <h1>基于Ajax简单的数据验证</h1>
    <hr />
    <div>
        <span>用户名:</span><input id="UserName" type="text" onblur="check();"/><span id="checkResult"></span>
    </div>
    <div>
        <span>密 码:</span><input id="PassWord" type="password" />
    </div> 
</body>
</html>


2.新建一个checkUser.xml文件
<?xml version="1.0" encoding="utf-8" ?>
<User>
 <UserName>admin</UserName>
 <PassWord>admin</PassWord>
</User>


3.新建一个checkUser.js文件
 

var xmlHttp;

function createXMLHttpRequest()
{
    if(window.ActiveXObject)
    {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if(window.XMLHttpRequest)
    {
        xmlHttp = new XMLHttpRequest();
    }
}

function check()
{
    createXMLHttpRequest();
    xmlHttp.onreadystatechange = handleStateChange;
    xmlHttp.open("GET","checkUser.xml");
    xmlHttp.send(null);
}

function handleStateChange()
{
   if(xmlHttp.readyState == 4)
   {
       if(xmlHttp.status ==200)
       {
           checkResult();
       }
   }
}

function checkResult()
{
    var xmlUser = xmlHttp.responseXML;
    var xmlUserName = xmlUser.getElementsByTagName("UserName")[0];
    if(document.getElementById("UserName").value == xmlUserName.childNodes[0].nodeValue)
        document.getElementById("checkResult").innerHTML = "用户名已没被注册了!!!";
    else
        document.getElementById("checkResult").innerHTML = "用户名还没被注册!!!";
}

完成~~!

posted @ 2007-11-12 11:22  强悍的抽屉  阅读(238)  评论(0编辑  收藏