简单的Ajax异步无刷新唯一性验证

admin 发布时间:2014-08-29 分类:.NET 阅读:3998次 3 条评论

超级简单的Ajax异步无刷新唯一性验证判断,常用在网页不刷新获取用户名、邮箱等是否存在。此文用的是简单的javascript+ASP.NET判断,也可以用Jquery Ajax框架等更加方便的使用Ajax的各种功能。

Javascript代码:

    <script type="text/javascript">
        //验证是否唯一
        var returnValue;
        var xmlHttp;
        function GetXmlHttpObject() {
            var xmlHttp = null;
            try {
                // Firefox, Opera 8.0+, Safari
                xmlHttp = new XMLHttpRequest();
            }
            catch (e) {
                //Internet Explorer
                try {
                    xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
                }
                catch (e) {
                    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
                }
            }
            return xmlHttp;
        }
        function CheckUnique() {
            xmlHttp = GetXmlHttpObject()
            if (xmlHttp == null) {
                alert("Browser does not support HTTP Request")
                return false;
            }
            //去掉所有空格replace(/\s+/g, "")
            var UserId =$("#<%=txtUserId.ClientID%>").val().replace(/\s+/g, "");
            var url = "../../HttpHandler/CheckUserUnique.ashx" + "?sid=" + Math.random();
            url = url + "&Num=" + UserId;
            xmlHttp.onreadystatechange = stateChanged;
            xmlHttp.open("GET", url, true);
            xmlHttp.send(null);
        }
        function stateChanged() {
            if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                returnValue = xmlHttp.responseText;
                if (returnValue == "true")
                    document.getElementById("worn").innerHTML = "该用户编号已经存在!";
                else
                    document.getElementById("worn").innerHTML = "*";
            }
        }
    </script>

ASP.NET后台CheckUserUnique.ashx页面代码,也可以使用普通aspx页面。

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string parmeter;
            if (context.Request.QueryString["Num"] == null || context.Request.QueryString["Num"].ToString() == "")
                parmeter = "0";
            else
                parmeter = context.Request.QueryString["Num"].ToString().Trim();
            string sql = "select * from UserInfo where StudentId='" + parmeter + "'";
            if (DbHelperSQL.Exists(sql))
            {
                context.Response.Write("true");
            }
            else
            {
                context.Response.Write("false");
            }
        }

使用ajax异步Javascript时候应该注意的问题。

1、请求的路径应该用相对路径。例如:(../../Ajax.aspx)

2、如果不是用的ashx,用的是aspx则需要在前台去掉form标签(去掉<form id="from1" runat="server">)

3、获取后台返回的字符串时候

            Response.Write("要返回客户端的字符串!");

            Response.Flush();//Flush立即发送缓冲区中的输出

            Response.End();//终止执行下面的输出语句!

4、最好用jQuery实现Ajax功能,比上javascript简洁的多、


关键字词: Ajax.NET

已有3条留言

发表评论:

◎欢迎您的参与讨论。