JQuery:AJAX-用户名验证
使用场景:注册新用户,验证新用户的用户名是否被使用:当用户的鼠标离开用户名窗口时,系统自动进行验证!
(1)HTML:
<!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>
<title>N0博客新用户注册</title>
<script src="js/jquery-1.2.6.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#divIndicator').ajaxStart(function(){$(this).show()})
.ajaxSuccess(function(){$(this).hide();})
.ajaxError(function(msg){$(this).hide();alert(msg);});
$('#userName').blur(function(){
var userName=$('#userName').val();
$.get('CubeHandler.ashx?userName='+userName,function(result){
alert(result);
});
});
});
</script>
<style type="text/css">
.indicator
{
color: #FF0000;
position: absolute;
top: 0px;
right: 0px;
display: none;
}
</style>
</head>
<body>
<div style="background: #eee; margin: 10% 10% 10% 10%;">
用户名:<input id="userName" type="text" />
<br />
<br />
密码:<input id="Password1" type="password" />
<br />
<br />
确认密码:<input id="Password2" type="password" />
</div>
<div id="divIndicator" class="indicator" style="background: #eee;">
loadinG……</div>
</body>
</html>
(2)CubeHandler.ashx(注:服务器验证代码可根据实际项目实现,此例不完整!)
<%@ WebHandler Language="C#" Class="CubeHandler" %>
using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Text;
using n0.DBUtility;
public class CubeHandler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
string userName = context.Request.Params["userName"];
context.Response.StatusCode = 200;
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
bool isPass = ValidateUserName(userName);
if (isPass)
{
context.Response.Write(string.Format("恭喜您,用户名 {0} 可以使用!", userName));
}
else {
context.Response.Write(string.Format("用户名 {0}已经被使用,请从新输入!", userName));
}
}
public bool IsReusable
{
get
{
return true;
}
}
public bool ValidateUserName(string userName)
{
string sqlstr = "select count(*) from n0_user where n0_userName='" + userName + "'";
int iCount = Convert.ToInt32(SqlHelper.ExecuteScalar(PubConstant.ConnectionString, CommandType.Text, sqlstr));
if (iCount == 1)
{
return false;
}
else
{
return true;
}
}
}