Asp.net实现无刷新检测用户名

本文将向大家介绍 ASP.NET实现无刷新检测用户名的方法,功能为:当用户输入用户名,用户名的文本框失去焦点后就检测用户名是否重复,不用再点击一个按钮才能检测(如今很多网站都具备这个功能哦)。

  下面就给出实现这一功能的代码:

  前台代码:

以下是引用片段:

<script type="text/javascript" language="Javascript">
        var XMLHttp = null;
        function CheckUser()
        {
            try
            {
                xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch(err1)
            {
                try
                {
                    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
                }
                catch(err2)
                {
                    xmlHttp = new XMLHttpRequest();
                }
            }
            var Text1 = document.getElementById("Text1");
            var url = "chkuser.aspx?User=" + Text1.value;
            XMLHttp.open("GET",url,true);
            XMLHttp.onreadystatechange = OnHandler;
            XMLHttp.send(null);

        }
        function OnHandler()
        {
            if(XMLHttp.readyState == 4)
            {
                var isValid = XMLHttp.responseText;
                var exists = document.getElementById("exsits");
                exists.innerHTML = isValid.substring(0,4);
            }
        }
</script>
<input id="Text1" type="text" onblur="CheckUser()" /><label d="exsits"></label><br />

  然后建一个chkuser.aspx,其后台代码改为:

以下是引用片段:

protected void Page_Load(object sender, EventArgs e)
    {
        string user = this.Request.QueryString["User"];

        if (UserExist(user))
        {
            Response.Write("存在");
        }
        else
        {
            Response.Write("不存在");
        }

    }

    private bool UserExist(string username)
    {
        ClassLib.Employee emp = new ClassLib.Employee();
        return emp.EmpNameExist(username);
    }

你可能感兴趣的:(asp.net)