原文  asp.net ajax检查用户名是否存在代码

用户注册时,我们经常需要检查用户名是否存在,本文就是实现无刷新验证用户名

打开开发环境VS 2005,新建项目(或打开现有项目),新建一个Web窗体,命名为 Default.aspx

创建 XMLHttpRequest 对象
所有现代浏览器 (IE7+、Firefox、Chrome、Safari 以及 Opera) 都内建了 XMLHttpRequest 对象。

通过一行简单的 JavaScript 代码,我们就可以创建 XMLHttpRequest 对象。

创建 XMLHttpRequest 对象的语法:
xmlhttp=new XMLHttpRequest();老版本的 Internet Explorer (IE5 和 IE6)使用 ActiveX 对象:
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");提示:在下一章,我们将使用 XMLHttpRequest 对象从服务器取回 XML 信息。

代码如下:

01.<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
02.<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
03.<html xmlns="http://www.w3.org/1999/xhtml" >  
04.<head runat="server">  
05.    <title>无标题页</title>  
06.    <script type="text/网页特效"><!--   
07.    var xmlHttp=null;        
08.          
09.        function createXMLHttpRequest()   
10.        {   
11.            if(xmlHttp == null){   
12.                if(window.XMLHttpRequest) {   
13.                    //Mozilla 浏览器   
14.                    xmlHttp = new XMLHttpRequest();   
15.                }else if(window.ActiveXObject) {   
16.                    // IE浏览器   
17.                    try {   
18.                        xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");   
19.                    } catch (e) {   
20.                        try {   
21.                            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");   
22.                        } catch (e) {   
23.                            //alert('创建失败');   
24.                        }   
25.                    }   
26.                }   
27.            }   
28.        }   
29.        function openAjax()   
30.        {     
31.            if( xmlHttp == null)   
32.            {                  
33.                createXMLHttpRequest();    
34.                if( xmlHttp == null)   
35.                {   
36.                    //alert('出错');   
37.                    return ;   
38.                }   
39.            }                          
40.              
41.            var val=document.getElementById('txt').value;              
42.                           
43.            xmlHttp.open("get","VerifyUserNameHandler.ashx?para="+val+"&date="+new Date(),true);               
44.            xmlHttp.onreadystatechange=xmlHttpChange;   
45.            xmlHttp.send(null);   
46.              
47.            document.getElementById('resultSpan').innerText='正在检查,请稍候...';   
48.        }   
49.          
50.        function xmlHttpChange()   
51.        {           
52.            if(xmlHttp.readyState==4)   
53.            {                               
54.                if(xmlHttp.status==200)   
55.                {            
56.                    var res=xmlHttp.responseText;                            
57.                    document.getElementById('resultSpan').innerText=res;   
58.                      
59.                    if(res=='恭喜,用户名可以使用。')   
60.                    {   
61.                        setTimeout("document.getElementById('resultSpan').innerText='';",2000);   
62.                    }   
63.                    else if(res=='抱歉,用户名已被使用。')   
64.                    {   
65.                        document.getElementById('txt').focus();   
66.                    }   
67.                }   
68.            }   
69.        }         
70.// --></script>  
71.</head>  
72.<body>  
73.    <form id="form1" runat="server">          
74.    用户名:<input type="text" id='txt' value="Sandy" onblur="openAjax();" />  <span id="resultSpan"></span>  
75.    </form>  
76.</body>  
77.</html>  
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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"><!--
    var xmlHttp=null;     
       
        function createXMLHttpRequest()
        {
            if(xmlHttp == null){
                if(window.XMLHttpRequest) {
                    //Mozilla 浏览器
                    xmlHttp = new XMLHttpRequest();
                }else if(window.ActiveXObject) {
                    // IE浏览器
                    try {
                        xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
                    } catch (e) {
                        try {
                            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
                        } catch (e) {
                            //alert('创建失败');
                        }
                    }
                }
            }
        }
        function openAjax()
        {  
            if( xmlHttp == null)
            {               
                createXMLHttpRequest(); 
                if( xmlHttp == null)
                {
                    //alert('出错');
                    return ;
                }
            }                       
           
            var val=document.getElementById('txt').value;           
                        
            xmlHttp.open("get","VerifyUserNameHandler.ashx?para="+val+"&date="+new Date(),true);            
            xmlHttp.onreadystatechange=xmlHttpChange;
            xmlHttp.send(null);
           
            document.getElementById('resultSpan').innerText='正在检查,请稍候...';
        }
       
        function xmlHttpChange()
        {        
            if(xmlHttp.readyState==4)
            {                            
                if(xmlHttp.status==200)
                {         
                    var res=xmlHttp.responseText;                         
                    document.getElementById('resultSpan').innerText=res;
                   
                    if(res=='恭喜,用户名可以使用。')
                    {
                        setTimeout("document.getElementById('resultSpan').innerText='';",2000);
                    }
                    else if(res=='抱歉,用户名已被使用。')
                    {
                        document.getElementById('txt').focus();
                    }
                }
            }
        }      
// --></script>
</head>
<body>
    <form id="form1" runat="server">       
    用户名:<input type="text" id='txt' value="Sandy" onblur="openAjax();" />  <span id="resultSpan"></span>
    </form>
</body>
</html>

然后新建一个一般处理程序,命名为 VerifyUserNameHandler.ashx

代码如下:

view plaincopy to clipboardprint?
01.<%@ WebHandler Language="C#" class="VerifyUserNameHandler" %>   
02.using System;   
03.using System.Web;   
04.using System.Collections;   
05.using System.Collections.Generic;   
06.public class VerifyUserNameHandler : IHttpHandler {   
07.      
08.    public void ProcessRequest (HttpContext context) {   
09.        //context.Response.ContentType = "text/plain";   
10.        string _name = context.Request.QueryString["para"];   
11.        _name = string.IsNullOrEmpty(_name) ? "" : _name;              
12.        System.Threading.Thread.Sleep(3000);//用线程来模拟数据库教程查询工作   
13.        string[] Names = new string[] { "Sandy", "阿非", "abc" };//这里用Names数组来代替数据库中的结果集   
14.        if (Array.IndexOf<string>(Names, _name) == -1)   
15.        {   
16.            context.Response.Write("恭喜,用户名可以使用。");   
17.        }   
18.        else  
19.        {   
20.            context.Response.Write("抱歉,用户名已被使用。");   
21.        }   
22.    }   
23.    
24.    public bool IsReusable {   
25.        get {   
26.            return false;   
27.        }   
28.    }   
29.}  
<%@ WebHandler Language="C#" class="VerifyUserNameHandler" %>
using System;
using System.Web;
using System.Collections;
using System.Collections.Generic;
public class VerifyUserNameHandler : IHttpHandler {
   
    public void ProcessRequest (HttpContext context) {
        //context.Response.ContentType = "text/plain";
        string _name = context.Request.QueryString["para"];
        _name = string.IsNullOrEmpty(_name) ? "" : _name;           
        System.Threading.Thread.Sleep(3000);//用线程来模拟数据库查询工作
        string[] Names = new string[] { "Sandy", "阿非", "abc" };//这里用Names数组来代替数据库中的结果集
        if (Array.IndexOf<string>(Names, _name) == -1)
        {
            context.Response.Write("恭喜,用户名可以使用。");
        }
        else
        {
            context.Response.Write("抱歉,用户名已被使用。");
        }
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }
}

到这里程序已经完成。

主要是利用了XMLHttpRequest对象采用异步的方式去访问服务器,获得响应后触发定义好的回调函数

本文是XMLHttpRequest对象异步方式对服务器发送Get方式的请求,访问服务器的文件为.ashx

asp.net ajax检查用户名是否存在代码的更多相关文章

  1. asp.net ajax 检测用户名是否可用代码

    原文  asp.net ajax 检测用户名是否可用代码 .net ajax 检测用户名是否可用代码 <script type="text/网页特效" src="c ...

  2. Ajax (Asynchronous javascript xml) 搜索框核心代码(JQuery) Ajax判断用户名存在核心代码 附:原生js的Ajax代码 其中有json的一句话解释

    前端 <script type="text/javascript"> $(function(){ $("#tid").keyup(function( ...

  3. ajax检查用户名重复

    1.获取ajax对象 new XMLHttpRequest(); IE6-8: new ActiveXOject("Microsoft.XMLHTTP"); 兼容判断:if(XML ...

  4. ajax检查用户名是否存在

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.c ...

  5. ajax检查用户名

    Ajax实现的效果 究竟Ajax能实现什么功能呢?今天下午学习了一下Ajax,现在跟大家分享一下我的学习心得.Ajax是什么?工作机制又是什么?可能不大准确,只是我个人看了视频学习后的一点点看法. A ...

  6. asp.net C#检查URL是否有效

    我们有时候需要对用户输入的网站(URL)进行有效性检查,  代码如下 复制代码 function CheckUrl(str) {    var RegUrl = new RegExp();    Re ...

  7. asp.net ajax实现md5加密

    1. [图片] asp.net ajax 效果截图.png 2. [代码]前端代码HTML/Javascript/jQuery <!DOCTYPE html PUBLIC "-//W3 ...

  8. 客户端调用服务器端方法——ASP.NET AJAX(Atlas)、Anthem.NET和Ajax.NET Professional实现之小小比较

    前几天曾经发过一篇<ASP.NET AJAX(Atlas)和Anthem.NET——管中窥豹般小小比较>,Jeffrey Zhao说用ASP.NET AJAX中的UpdatePanel似乎 ...

  9. AJAX异步检查,检查用户名是否存在

    AJAX异步检查,检查用户名是否存在 写法一: var xmlHttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, ...

随机推荐

  1. linux下I2C驱动

    2C协议规定了主机和从机的概念,在驱动中采用的多是适配器(主机)和设备(从机).首先,i2c规定  Bus    -> Algorithm  算法               Adapter   ...

  2. Linux c c++ 开发调试技巧

    看到一篇介绍 linux c/c++ 开发调试技巧的文章,感觉挺使用,哪来和大家分享. 通向 UNIX 天堂的 10 个阶梯Author: Arpan Sen, 高级技术人员, Systems Doc ...

  3. [转]给Linux系统管理员准备的Nmap命令的29个实用范例+ tsysv 系统服务器管理器

    原文链接:http://os.51cto.com/art/201401/428152.htm Nmap即网络映射器对Linux系统/网络管理员来说是一个开源且非常通用的工具.Nmap用于在远程机器上探 ...

  4. linux中如何修改文件夹的用户权限 chown命令

    linux中,可以使用chown命令来修改文件夹的用户权限. 1.  以普通用户 A 登录linux,利用su -切换到root用户 2. 在root用户下,可以看到文件夹内容 3. 但通过文件系统, ...

  5. pyfits 读取bintable

    import pyfits as pf import numpy as np import math import pandas as pd import matplotlib.pyplot as p ...

  6. 10-UIKit(UIDatePicker、UIPickerView、UIWebView、Storyboard)

    目录: 1. UIDatePicker 2. UIPickerView 3. UIPickerView多列关联 4. UIWebView 5. Storyboard(故事板) 回到顶部 1. UIDa ...

  7. WCF技术剖析之三十:一个很有用的WCF调用编程技巧[下篇]

    原文:WCF技术剖析之三十:一个很有用的WCF调用编程技巧[下篇] 在<上篇>中,我通过使用Delegate的方式解决了服务调用过程中的异常处理以及对服务代理的关闭.对于<WCF技术 ...

  8. boost 分析命令行参数

    #include <boost/program_options.hpp> #include <iostream> #include <vector> using n ...

  9. 怎样实现cocos2d-x之文字渲染

    // 1.创建一段文本 // create函数的三个参数分别为:文本内容.字体和字体大小 CCLabelTTF *font=CCLabelTTF::create("Hello World&q ...

  10. C中嵌入SQL

    连接到SAMPLE数据库,查询LASTNAME为JOHNSON的FIRSTNAME信息. #include <stdio.h> #include <stdlib.h> #inc ...