本文将向大家介绍Asp.net实现无刷新检测用户名的方法,功能为:当用户输入用户名,用户名的文本框失去焦点后就检测用户名是否重复,不用再点击一个按钮才能检测(如今很多网站都具备这个功能哦)。
下面就给出实现这一功能的代码:
前台代码:
<
script
type
="text/javascript"
language
="javascript"
>
var xmlHttp = null ;
function CheckUser()
{
try
{
xmlHttp = new ActiveXObject( " Msxml2.XMLHTTP " );
}
catch (err1)
{
try
{
xmlHttp = new ActiveXObject( " Microsoft.XMLHTTP " );
}
catch (err2)
{
xmlHttp = new XMLHttpRequest();
}
}
var Text1 = document.getElementById( " Text1 " );
var url = " chkuser.aspx?User= " + Text1.value;
xmlHttp.open( " GET " ,url, true );
xmlHttp.onreadystatechange = OnHandler;
xmlHttp.send( null );
}
function OnHandler()
{
if (xmlHttp.readyState == 4 )
{
var isValid = xmlHttp.responseText;
var exists = document.getElementById( " exsits " );
exists.innerHTML = isValid.substring( 0 , 4 );
}
}
</ script >
< input id ="Text1" type ="text" onblur ="CheckUser()" />< label d ="exsits" ></ label >< br />
var xmlHttp = null ;
function CheckUser()
{
try
{
xmlHttp = new ActiveXObject( " Msxml2.XMLHTTP " );
}
catch (err1)
{
try
{
xmlHttp = new ActiveXObject( " Microsoft.XMLHTTP " );
}
catch (err2)
{
xmlHttp = new XMLHttpRequest();
}
}
var Text1 = document.getElementById( " Text1 " );
var url = " chkuser.aspx?User= " + Text1.value;
xmlHttp.open( " GET " ,url, true );
xmlHttp.onreadystatechange = OnHandler;
xmlHttp.send( null );
}
function OnHandler()
{
if (xmlHttp.readyState == 4 )
{
var isValid = xmlHttp.responseText;
var exists = document.getElementById( " exsits " );
exists.innerHTML = isValid.substring( 0 , 4 );
}
}
</ script >
< input id ="Text1" type ="text" onblur ="CheckUser()" />< label d ="exsits" ></ label >< br />
然后建一个chkuser.aspx,其后台代码改为:
protected
void
Page_Load(
object
sender, EventArgs e)
{
string user = this .Request.QueryString[ " User " ];
if (UserExist(user))
{
Response.Write( " 存在 " );
}
else
{
Response.Write( " 不存在 " );
}
}
private bool UserExist( string username)
{
// 以下判断用户是否在在的方法根据实际情况而定
ClassLib.Employee emp = new ClassLib.Employee();
return emp.EmpNameExist(username);
}
{
string user = this .Request.QueryString[ " User " ];
if (UserExist(user))
{
Response.Write( " 存在 " );
}
else
{
Response.Write( " 不存在 " );
}
}
private bool UserExist( string username)
{
// 以下判断用户是否在在的方法根据实际情况而定
ClassLib.Employee emp = new ClassLib.Employee();
return emp.EmpNameExist(username);
}
OK,代码就这么多,主要是体现一下思路。