AJAX 学习笔记[八] AJAX 制作可自动校验的表单

来源:互联网 发布:java if else 缩写 编辑:程序博客网 时间:2024/05/16 13:03

客户端代码(9-9.html ):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>

<head>

<title>自动校验的表单</title>

<style type="text/css">

<!--

form{

    padding:0px; margin:0px;

    font-size:12px;

    font-family:Arial, Helvetica, sans-serif;

}

input{

    border:1px solid #004082;

    font-size:12px;

    font-family:Arial, Helvetica, sans-serif;

}

-->

</style>

<script language="javascript">

var xmlHttp;

function createXMLHttpRequest(){

    if(window.ActiveXObject)

        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

    else if(window.XMLHttpRequest)

        xmlHttp = new XMLHttpRequest();

}

function showResult(sText){

    var oSpan = document.getElementById("UserResult");

    oSpan.innerHTML = sText;

    if(sText.indexOf("already exists") >= 0)

        //如果用户名已被占用

        oSpan.style.color = "red";

    else

        oSpan.style.color = "black";

}

function startCheck(oInput){

    //首先判断是否有输入,没有输入直接返回,并提示

    if(!oInput.value){

        oInput.focus();      //聚焦到用户名的输入框

        document.getElementById("UserResult").innerHTML = "User cannot be empty.";

        return;

    }

    //创建异步请求

    createXMLHttpRequest();

    var sUrl = "9-9.aspx?user=" + oInput.value.toLowerCase() + "&timestamp=" + new Date().getTime();

    xmlHttp.open("GET",sUrl,true);

    xmlHttp.onreadystatechange = function(){

        if(xmlHttp.readyState == 4 && xmlHttp.status == 200)

            showResult(xmlHttp.responseText);   //显示服务器结果

    }

    xmlHttp.send(null);

}

</script>

</head>

<body>

<form name="register">

<table cellpadding="5" cellspacing="0" border="0">

    <tr><td>用户名:</td><td><input type="text" onblur="startCheck(this)" name="User"></td> <td><span id="UserResult"></span></td> </tr>

    <tr><td>输入密码:</td><td><input type="password" name="passwd1"></td> <td></td> </tr>

    <tr><td>确认密码:</td><td><input type="password" name="passwd2"></td> <td></td> </tr>

    <tr>

        <td colspan="2" align="center">

        <input type="submit" value="注册">

        <input type="reset" value="重置">

        </td> <td></td>

    </tr>

</table>

</form>

</body>

</html>

 

服务器端代码(9-9.aspx ):

<%@ Page Language="C#" ContentType="text/html" ResponseEncoding="gb2312" %>

<%@ Import Namespace="System.Data" %>

<%

    Response.CacheControl = "no-cache";

    Response.AddHeader("Pragma","no-cache");

   

    if(Request["user"]=="isaac")

        Response.Write("Sorry, " + Request["user"] + " already exists.");

    else

        Response.Write(Request["user"]+" is ok.");

%>