用ajax实现的用户注册,作为自己在博客园的第一份礼物送给大家

本人也是初学ajax,通过做这个注册功能,对ajax的原理有了更深入的了解,希望能帮到那些正在学习ajax的朋友。主要代码如下:
Register.aspx(前台代码)

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Register.aspx.cs" Inherits="Register" %>

<!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 runat="server">
    <title>无标题页</title>

    <script type="text/javascript" src="js/User.js"></script>

    <script type="text/javascript" language="javascript">
        function change()
        {
        var img =document.getElementById("imgCheck");
        img.src=img.src+'?';
        }
    </script>

</head>

<script src="js/addr.js" type="text/javascript" language="javascript"></script>

<script src="js/func.js" type="text/javascript" language="javascript"></script>

<body>
    <table border="0" cellpadding="5" cellspacing="0" width="650px">
        <tr valign="top">
            <td>
                账号:&nbsp;<font color="#ff0000">*</font>
            </td>
            <td>
                <input id="txtName" type="text" onblur="j_username()" onkeyup="checkName(document.getElementById('txtName').value)" />
                <img id="imgName" alt="" src="" style="vertical-align: top; display: none" />
                <span id="NameError" style="color: #ff0033;"></span>
                <br />
                <font color="gray" size="2">账号只能是字母,数字,下划线(_)或其组合,并且以字母为开头长度的5-18个字符。</font>
            </td>
        </tr>
        <tr>
            <td>
                生日:
            </td>
            <td>
                <select id="year" size="1" onchange="showmonth();showday()">
                    <option value="">请选择年份...</option>

                    <script type="text/javascript">
                        var elYear=document.getElementById("year");
                        var yearbegin=1900,yearend=2009;
                        for(var i=yearbegin;i<=yearend;i++)
                        {
                            elYear.options.add(new Option(i+1, i+1));
                        }
                    </script>

                </select>
                <font size="2">年</font>
                <select id="month" size="1" onchange="showday();">
                    <option value="">请选择月份...</option>
                </select>
                <font size="2">月</font>
                <select id="day" size="1">
                    <option value="">请选择日期...</option>
                </select>
                <font size="2">日</font>
            </td>
        </tr>
        <tr>
            <td>
                性别:
            </td>
            <td>
                <input id="radioMan" name="radioSex" type="radio" checked="checked" />
                男
                <input id="radioWoman" name="radioSex" type="radio" />
                女
            </td>
        </tr>
        <tr valign="top">
            <td>
                密码:&nbsp;<font color="#ff0000">*</font>
            </td>
            <td>
                <input id="txtPwd" type="password" onblur="j_password()" style="width: 151px" />
                <img id="imgPwd" alt="" src="" style="vertical-align: top; display: none" />
                <span id="PwdError" style="color: #ff0033;"></span>
                <br />
                <font color="gray" size="2">密码只能是6-12位字母,数字或二者结合,区分大小写。</font>
            </td>
        </tr>
        <tr>
            <td>
                确认密码:&nbsp;<font color="#ff0000">*</font>
            </td>
            <td>
                <input id="txtPwd_AG" type="password" onblur="j_password1()" style="width: 151px" />
                <img id="imgPwd_AG" alt="" src="" style="vertical-align: top; display: none" />
                <span id="PwdError2" style="color: #ff0033;"></span>
            </td>
        </tr>
        <tr>
            <td>
                邮箱:&nbsp;<font color="#ff0000">*</font>
            </td>
            <td>
                <input id="txtEmail" type="text" onblur="j_email()" />
                <img id="imgEmail" alt="" src="" style="vertical-align: top; display: none" />
                <span id="EmailError" style="color: #ff0033;"></span>
            </td>
        </tr>
        <tr>
            <td>
                所在地:
            </td>
            <td>
                <select id="province" name="province">
                </select>
                <select id="city" name="city">
                </select>
                <select id="area" name="area">
                </select>
            </td>
        </tr>
        <tr valign="top">
            <td>
                验证码:&nbsp;<font color="#ff0000">*</font>
            </td>
            <td>
                <input id="txtValCode" type="text" style="width: 40px" />
                <span id="ValCodeError" style="color: #ff0033;"></span>
                <img id="imgCheck" src="ValidateCode.aspx" alt="单击图片" title="看不清?换张图片" style="vertical-align: top;
                    cursor: pointer" onclick="this.src='ValidateCode.aspx?'+new Date()" /><a style="color: Blue"
                        href="javascript:change();"><font size="2">看不清?点此更换</font></a>
            </td>
        </tr>
        <tr>
            <td>
            </td>
            <td>
                <input id="btnReg" type="button" value="注册" onclick="regUser()" />&nbsp;&nbsp;
                <input id="btnClear" type="button" value="重置" onclick="j_clear()" />
            </td>
        </tr>
    </table>

    <script type="text/javascript" src="js/SelectDate.js"></script>

</body>
</html>

<script type="text/javascript" language="javascript" defer="defer">
        new GETADDR("province","city","area");
</script>

 
User.js(主要javascript代码)

//声明XMLHttpRequest对象
var xmlHttp;
var canSubmit=false;

//检测用户名是否存在
function checkName(userName)
{
    createXMLHTTP();//创建XMLHttpRequest对象
    var url="DisposeEvent.aspx?name="+userName+"&event=Check";
    xmlHttp.open("GET",url,true);
    xmlHttp.onreadystatechange=checkUserName;
    xmlHttp.send(null);
}

function createXMLHTTP()
{
    if(window.XMLHttpRequest)
    {
        xmlHttp=new XMLHttpRequest();//mozilla浏览器
    }
    else if(window.ActiveXObject)
    {
        try
        {
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");//IE老版本
        }
        catch(e)
        {}
        try
        {
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");//IE新版本
        }
        catch(e)
        {}
        if(!xmlHttp)
        {
            window.alert("不能创建XMLHttpRequest对象实例!");
            return false;
        }
    }
}

//执行检测用户名回调函数
function checkUserName()
{
    if(xmlHttp.readyState==4)//判断对象状态
    {
        if(xmlHttp.status==200)//信息成功返回,开始处理信息
        {
            if(xmlHttp.responseText=="true")
            {
                document.getElementById("imgName").style.display="";
                document.getElementById("imgName").src="images/true.gif";
                document.getElementById("NameError").innerHTML="<font color=\"red\">恭喜您,该用户名无人使用!<font>";
                //让注册按钮失效
                document.getElementById("btnReg").disabled=false;
            }
            else
            {
                document.getElementById("imgName").style.display="";
                document.getElementById("imgName").src="images/false.gif";
                document.getElementById("NameError").innerHTML="<font color=\"red\">对不起,您注册的用户名已经存在!<font>";
                document.getElementById("btnReg").disabled=true;                        
            }
        }
    }
}

//注册新用户
function regUser()
{
    var submitOK=true;
    canSubmit=true;
    j_username();
    submitOK=submitOK&canSubmit;
    j_password();
    submitOK=submitOK&canSubmit;
    j_password1();
    submitOK=submitOK&canSubmit;
    j_email();
    submitOK=submitOK&canSubmit;
    submitOK=submitOK&canSubmit;
    if(canSubmit==false||submitOK==0)
    {
        return;
    }
    var iSex;
    var obj=document.getElementsByName("radioSex");
    if(obj[0].checked)
    {
        iSex=1;
    }
    else
    {
        iSex=2;
    }
    var url="DisposeEvent.aspx?name="+document.getElementById("txtName").value+"&password="+document.getElementById("txtPwd").value+"&event=Reg";
    url+="&email="+document.getElementById("txtEmail").value+"&sex="+iSex;
    url+="&year="+document.getElementById("year").value+"&month="+document.getElementById("month").value+"&day="+document.getElementById("day").value;
    url+="&province="+encodeURI(document.getElementById("province").value)+"&city="+encodeURI(document.getElementById("city").value)+"&area="+encodeURI(document.getElementById("area").value);
    xmlHttp.open("GET",url,true);
    xmlHttp.onreadystatechange=regUserInfo;
    xmlHttp.send(null);
}

//注册用户回调函数
function regUserInfo()
{
    if(xmlHttp.readyState==4)//判断对象状态
    {
        if(xmlHttp.status==200)//信息成功返回,开始处理信息
        {
            if(xmlHttp.responseText=="true")//获取的Response.Write("true");里面的文本
            {
                alert("恭喜,新用户注册成功!");            
            }
            else
            {
                alert("对不起,注册失败!");
                                      
            }
            j_clear();
        }
    }
}

function j_username()
{
    document.getElementById("NameError").innerHTML="";
    var username=document.getElementById("txtName").value;
    var reg="[^a-zA-Z_0-9]";
    var reg1="\\D";
    if(username=="")
    {
        document.getElementById("imgName").style.display="";
        document.getElementById("imgName").src="images/false.gif";
        document.getElementById("NameError").innerHTML="<font color=\"red\">用户名不能为空!<font>";
        canSubmit=false;
        return;
    }
    else if(username.length<5||username.length>18)
    {
        document.getElementById("imgName").style.display="";
        document.getElementById("imgName").src="images/false.gif";
        document.getElementById("NameError").innerHTML="<font color=\"red\">用户名长度不符合要求!长度必须为5-18位!<font>";
        canSubmit=false;
        return;
    }
    else if(!username.substring(0,1).match(reg1))
    {
        document.getElementById("imgName").style.display="";
        document.getElementById("imgName").src="images/false.gif";
        document.getElementById("NameError").innerHTML="<font color=\"red\">必须以字母开头!<font>";
        canSubmit=false;
        return;
    }
    else if(username.match(reg))
    {
        document.getElementById("imgName").style.display="";
        document.getElementById("imgName").src="images/false.gif";
        document.getElementById("NameError").innerHTML="<font color=\"red\">用户名只能是字母,数字,下划线!<font>";
        canSubmit=false;
        return;
    }
    document.getElementById("NameError").innerHTML="";
    canSubmit=true;
}

function j_password()
{
    var password=document.getElementById("txtPwd").value;
    if(password.length<6||password.length>12)
    {
        document.getElementById("imgPwd").style.display="";
        document.getElementById("imgPwd").src="images/false.gif";
        document.getElementById("PwdError").innerHTML="<font color=\"red\">密码长度不正确!<font>";
        canSubmit=false;
        return;
    }
    if(document.getElementById("txtName").value==password)
    {
        document.getElementById("imgPwd").style.display="";
        document.getElementById("imgPwd").src="images/false.gif";
        document.getElementById("PwdError").innerHTML="<font color=\"red\">用户名和密码不能相同,请使用新的密码!<font>";
        canSubmit=false;
        return;
    }
    var reg="\\W";
    if(password.match(reg))
    {
        document.getElementById("imgPwd").style.display="";
        document.getElementById("imgPwd").src="images/false.gif";
        document.getElementById("PwdError").innerHTML="<font color=\"red\">密码只能是英文或者数字!<font>";
        canSubmit=false;
        return;
    } 
    document.getElementById("imgPwd").style.display=""; 
    document.getElementById("imgPwd").src="images/true.gif";
    document.getElementById("PwdError").innerHTML="";
    canSubmit=true;
}

function j_password1()
{
    var password=document.getElementById("txtPwd_AG").value;
    if(password=="")
    {
        document.getElementById("imgPwd_AG").style.display="";
        document.getElementById("imgPwd_AG").src="images/false.gif";
        document.getElementById("PwdError2").innerHTML="<font color=\"red\">请输入确认密码!<font>";
        canSubmit=false;
        return;
    }
    if(password!=document.getElementById("txtPwd").value)
    {
        document.getElementById("imgPwd_AG").style.display="";
        document.getElementById("imgPwd_AG").src="images/false.gif";
        document.getElementById("PwdError2").innerHTML="<font color=\"red\">两次输入的密码不一致,请重新输入!<font>";
        document.getElementById("txtPwd_AG").value="";
        canSubmit=false;
        return;
    }
    document.getElementById("imgPwd_AG").style.display="";
    document.getElementById("imgPwd_AG").src="images/true.gif";
    document.getElementById("PwdError2").innerHTML="";
    canSubmit=true;
}

function j_email()
{
    var email=document.getElementById("txtEmail").value;
    var reg=/^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@(([0-9a-zA-Z])+([-\w]*[0-9a-zA-Z])*\.)+[a-zA-Z]{2,9})$/;
    if(!email.match(reg))
    {
        document.getElementById("imgEmail").style.display="";
        document.getElementById("imgEmail").src="images/false.gif";
        document.getElementById("EmailError").innerHTML="<font color=\"red\">邮件地址无效!<font>";
        canSubmit=false;
        return;
    }
    document.getElementById("imgEmail").style.display="";
    document.getElementById("imgEmail").src="images/true.gif";
    document.getElementById("EmailError").innerHTML="";
    canSubmit=true;
}

function j_clear()
{
    document.getElementById("txtName").value="";
    document.getElementById("year").value="";
    document.getElementById("month").value="";
    document.getElementById("day").value="";
    document.getElementById("txtPwd").value="";
    document.getElementById("txtPwd_AG").value="";
    document.getElementById("txtEmail").value="";
    document.getElementById("radioMan").checked="checked";
    document.getElementById("txtValCode").value="";
    document.getElementById("province").value="";
    document.getElementById("city").value="";
    document.getElementById("area").value="";
    document.getElementById("imgName").style.display="none";
    document.getElementById("imgPwd").style.display="none";
    document.getElementById("imgPwd_AG").style.display="none";
    document.getElementById("imgEmail").style.display="none";
    document.getElementById("NameError").innerHTML="";
    document.getElementById("PwdError").innerHTML="";
    document.getElementById("PwdError2").innerHTML="";
    document.getElementById("EmailError").innerHTML="";
}


DisposeEvent.aspx.cs(客户端与服务器的交互页面后台代码)

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using netschool;

public partial class DisposeEvent : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        User cUser = new User();
        //是否为执行CheckName方法
        if (Request.QueryString["event"].ToString() == "Check")
        {
            if (cUser.CheckUserName(Request.QueryString["name"].ToString()))
            {
                //当数据库中已存在此用户时输出为false,让其显示相应图标
                Response.Write("false");
                Response.End();
            }
            else
            {
                Response.Write("true");
                Response.End();
            }
        }

        //是否为执行regUser方法
        if (Request.QueryString["event"].ToString() == "Reg")
        {
            string strName = Request.QueryString["name"].ToString();        
            string strPwd = Request.QueryString["password"].ToString();
            string strEmail = Request.QueryString["email"].ToString();
            int iSex = Convert.ToInt32(Request.QueryString["sex"]);
            string strYear = Request.QueryString["year"].ToString();
            string strMonth = Request.QueryString["month"].ToString();
            string strDay = Request.QueryString["day"].ToString();
            string strProvince = Request.QueryString["province"].ToString();
            string strCity = Request.QueryString["city"].ToString();
            string strArea = Request.QueryString["area"].ToString();
            if (!cUser.AddUser(strName,strPwd,strEmail,iSex,strYear,strMonth,strDay,strProvince,strCity,strArea))
            {
                Response.Write("true");//客户端用responseText接收
                Response.End();
            }
        }
    }
}


上面只给出了部分重要代码,仅供初学ajax的朋友学习和参考,如有不明之处,可联系本人qq:460730136

posted @ 2010-03-24 12:53  zhongnanmikky  阅读(1225)  评论(5编辑  收藏  举报