TestCode

博客园 首页 新随笔 联系 订阅 管理

下面是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 }

欢迎大家批评指正!

posted on 2011-06-25 20:38  yaoguipeng  阅读(2095)  评论(3编辑  收藏  举报