用Ajax判断用户名是否存在

本文介绍了一个简单的JavaScript函数,用于验证用户输入的用户名是否为空,并通过Ajax调用服务器端程序检查用户名是否已被占用。服务器端使用C#处理请求并返回用户名是否可用的状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    <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;
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值