<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!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 language="javascript" type="text/javascript">
function send_request(flag)
{
//创建XMLHttpRequest;
http_request = false;
if(window.XMLHttpRequest)
{
// 非IE 浏览器
http_request = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
//IE
try
{
http_request = new ActiveXObject("Msxml2.XMLHTTP");//较新版本的IE
}catch(e)
{
try
{
http_request = new ActiveXOBject("Microsoft.XMLHTTP");//旧版本IE
}catch(e){}
}
}
else
{
window.alert("不能创建 XMLHttpRequest对象,无法应用Ajax");
return false;
}
//指定回调函数
if(flag == "addAdmin")
{
http_request.onreadystatechange = addAdmin;
//创建HTTP请求
http_request.open("get","Handler.ashx?flag=addAdmin&userName="+document.getElementById("txtUserName").value,true);
}
//发送上面创建的HTTP请求
http_request.send(null);
}
function addAdmin()
{
if(http_request.readyState == 4)//发送成功
{
if(http_request.status == 200)//交易成功
{
//正式处理有信息
if(http_request.responseText == "该用户已经存在")
{
//隐藏提交按扭
//该用户已经存在
}
else
{
//该用户已经不存在
}
document.getElementById("lblShow").innerText=http_request.responseText;
}
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="txtUserName" runat="server" onBlur="send_request('addAdmin');" /><span id="lblShow" />
<%-- onBlur 失去焦点时发生 --%>
</form>
</body>
</html>
一般处理程序文件: Handler.ashx
<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using DBUtility;
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
string flag = context.Request.QueryString["flag"].ToString();
if (flag.Equals("addAdmin"))
{
string userName = context.Request.QueryString["userName"].ToString();
string strSql = "select count(*) from TB_Admin where admin_name='" + userName + "' ";
if (DbHelperSQL.Exists(strSql)==true)
{
context.Response.Write("该用户已经存在");
}
else
{
context.Response.Write("恭喜, 你可以注册" + userName);
}
}
}
public bool IsReusable {
get {
return false;
}
}
}
文本框失去焦点后: