用Ajax判断用户名是否存在

来源:互联网 发布:智能电视软件下载 编辑:程序博客网 时间:2024/06/06 06:35
    <script language="javascript" type="text/javascript">
    
var xmlHttp
    
function getIsName()
    {
        
if(document.getElementById("txtName").value=="")
        {
            document.getElementById(
"lblName").innerHTML="<font color=red>用户名不能为空</font>";
        }
        
else
        {
            
            createXMLHttpRequest();
            xmlHttp.onreadystatechange
=getName;
            xmlHttp.open(
"GET","getName.ashx?name="+document.getElementById("txtName").value,true);
            xmlHttp.send(
null);
        }
        
    }
    
function createXMLHttpRequest()
    {
        
if(window.ActiveXObject)
        {            
            xmlHttp
=new ActiveXObject("MicroSoft.XMLHttp");
        }
        
else if(window.XMLHttpRequest)
        {
            xmlHttp
=new XMLHttpRequest();
        }
    }
    
function getName()
    {
        
if(xmlHttp.readyState==4)
            
if(xmlHttp.status==200)
            {
                document.getElementById(
"lblName").innerHTML=xmlHttp.responseText;
            }
    }
    
    
    
    
    
</script>

 

触发

                        <tr>
                            
<td style="width: 80px" align="right">
                                用户名
</td>
                            
<td colspan="2">
                                
<input id="txtName" type="text" runat="server" onblur="getIsName();" maxlength="12" />
                                
<asp:Label ID="lblName" runat="server"></asp:Label></td>
                        
</tr>

getName.ashx  (处理页面)

<%@ WebHandler Language="C#" Class="getName" %>

using System;
using System.Web;

public class getName : IHttpHandler 
{
    
    
public void ProcessRequest (HttpContext context) 
    {
        context.Response.ContentType 
= "text/plain";
        
string userName = context.Request.QueryString["name"];
        DB getNameManager 
= new DB();
        
if (getNameManager.userIsName(userName))
        {
            context.Response.Write(
"<font color=green>此用户名可以注册</font>");
        }
        
else
        {
            context.Response.Write(
"<font color=red>此用户名已存在</font>");
        }
    }
 
    
public bool IsReusable 
    {
        
get 
        {
            
return false;
        }
    }

}