每天进步一点点 用AJAX自动校验用户名是否与已有用户名重复

下面是CheckUserName.htm页面的代码

 
  
1 < html xmlns = " http://www.w3.org/1999/xhtml " >
2   < head >
3 < title > 无标题页 < / title>
4 < script src = " http://www.cnblogs.com/../JQuery/js/jquery-1.4.2.js " type = " text/javascript " >< / script>
5 < script type = " text/javascript " >
6 $( function (){
7 $( " #textUserName " ).blur( function (){ // 鼠标离开文本框时触发
8 var username = $( " #textUserName " ).val();
9 // 向CheckUserName发出请求,参数username,返回的数据用function(data,satus){}处理
10 $.post( " CheckUserName.ashx " ,{ " username " :username}, function (data,status){
11 if (status == " success " ){
12 alert(data);
13 }
14 });
15 })
16 });
17 < / script>
18 < / head>
19 < body >
20 < input type = " text " id = " textUserName " / >
21 < / body>
22 < / html>

下面的是CheckUserName.ashx页面的内容。

 
  
1 using System;
2 using System.Web;
3 using System.Data.SqlClient;
4 using System.Configuration;
5
6 public class CheckUserName : IHttpHandler {
7
8 public void ProcessRequest (HttpContext context) {
9 context.Response.ContentType = " text/plain " ;
10 string username = context.Request[ " username " ];
11 string connection = ConfigurationManager.ConnectionStrings[ " TestDBConnectionString " ].ConnectionString;
12 using (SqlConnection sqlconn = new SqlConnection(connection))
13 {
14 using (SqlCommand sqlcommand = new SqlCommand())
15 {
16 sqlcommand.Connection = sqlconn;
17 sqlcommand.CommandText = " select * from UserNameLoginCheck where LoginUserName = @username " ;
18 sqlcommand.Parameters.AddWithValue( " @username " , username);
19 int SelectCount;
20 try
21 {
22 sqlconn.Open();
23 using (SqlDataReader sqldatareader = sqlcommand.ExecuteReader())
24 {
25 // 如果有找到,sqldatareader.Read()执行结果为true,否则为false.
26 while (sqldatareader.Read())
27 {
28 context.Response.Write( " 用户名已存在,请重新选择 " ); return ;
29 }
30 context.Response.Write( " 用户名可用 " ); return ;
31 }
32 }
33 catch (Exception ee)
34 {
35 throw ee;
36 }
37 finally
38 {
39 sqlconn.Close();
40 sqlconn.Dispose();
41 sqlcommand.Dispose();
//这个地方感觉有点多余,因为后面出了using的范围系统会自动注销sqlconn和sqlcommand,不知道大家怎么看呢?
42 }
43 }
44 }
45 }
46
47 public bool IsReusable {
48 get {
49 return false ;
50 }
51 }
52
53 }

欢迎大家批评指正!

转载于:https://www.cnblogs.com/TestCode/archive/2011/06/25/2090365.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值