<!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>Register</title>
<script type="text/javascript">
//声明一个全局变量,用来保存XMLHttpRequest对象的引用(未初始化)
var xmlHttp = false;
//创建XMLHttpRequest对象函数
function GetXMLHttpRequest()
{
// 由于 XMLHttpRequest 对象在各个浏览器中实现机制不同,所以要综合考虑
var xmlHttp = false;
//如果是Mozilla浏览器
if (!xmlHttp && typeof XMLHttpRequest != 'object') //undefined
{
xmlHttp = new XMLHttpRequest();
}
//如果是IE浏览器
else if(window.ActiveXObject)
{
try
{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e2)
{
xmlHttp = false;
}
}
}
return xmlHttp;
}
//当用户名文本框失去输入焦点时响应
function checkUserName()
{
// 检查文本框是否有输入
var txtUserName = document.getElementById('txtUserName');
if (txtUserName.value == "")
return;
xmlHttp = GetXMLHttpRequest();
// 构造将XMLHttpRequest对象将请求的服务器端的URL字符串
var url = "CheckUserName.aspx?UserName=" + txtUserName.value;
// 建立与服务器端的连接
xmlHttp.open("GET", url, true);
// 设置回调函数
xmlHttp.onreadystatechange = callBack_CheckUserName;
// 发送请求
xmlHttp.send(null);
}
//处理响应
function callBack_CheckUserName()
{
var lblMessage = document.getElementById("lblMessage");
// 4代表服务器端执行完毕并已经成功返回
if (4 == xmlHttp.readyState)
{
if(200 == xmlHttp.status)
{
//通过responseText属性得到服务器端实际返回的文本
var isValid = xmlHttp.responseText;
//根据isValid的值决定lblNameMessage的显示内容
lblMessage.innerHTML = (isValid.toLowerCase() == "true") ? "用户名可用" : "用户名已被注册";
}
}
else
{
lblMessage.innerHTML = "数据查询中...";
}
}
</script>
</HEAD>
<body>
<form method="post" action="">
<div>
用户名:
<input type="text" id="txtUserName" name="txtUserName" οnblur="return checkUserName();"/>
<span id="lblMessage"></span><br>
密 码:
<input type="password" id="txtPassword" name="txtPassword" /><br>
<input type="submit" id="btnRegister" name="btnRegister" value="注册" />
</div>
</form>
</body>
</html>
CheckUserName.aspx.cs
C# codeusing System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class CheckUserName : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// 得到用户选择的用户名
string username = Request.QueryString["UserName"];//Request["UserName"]
// 模拟验证 实际应用中应查询数据库
bool isValid = false;
if (String.Compare(username, "amandag", true) != 0)
{
isValid = true;
}
Response.Clear();
Response.ContentType = "text/html";
Response.Write(isValid.ToString());
Response.End();
Response.Close();
}
}