前台页面代码:
<!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>检测用户名是否可用</title>
<style type="text/css">
.ErrSyt
{
font-size: 20px;
}
.ErrMsg
{
color: Red;
}
</style>
<script type="text/javascript" language="javascript">
var xmlHttp = null;
function chenkUserName() {
if (window.XMLHttpRequest) {//非IE浏览器
xmlHttp = new XMLHttpRequest(); //创建xmlHttp对象
} else if (window.ActiveXObject) {//IE6以下浏览器
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); //创建xmlHttp对象
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); //创建xmlHttp对象
}
catch (ex) { }
}
}
var name = document.getElementById("txtUserName").value;
xmlHttp.open("POST", "Reg_GetUserName.aspx?name=" + encodeURI(name));
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
if (xmlHttp.responseText == "ok") {
document.getElementById("lblErrMsg").innerHTML = name + " 已存在";
} else {
document.getElementById("lblErrMsg").innerHTML = name + " 可以使用";
}
}
}
xmlHttp.send(null);
}
</script>
</head>
<body>
<span>昵称:</span><input type="text" id="txtUserName" οnblur="chenkUserName()" /><label
class="ErrSyt ErrMsg" id="lblErrMsg" title=""></label><br />
<span>密码:</span><input type="text" /><br />
<input type="button" value="注册" />
</body>
</html>
服务器端代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
namespace AjaxTest._0818d_emos
{
public partial class Reg_GetUserName : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//查询语句
string name = Request.QueryString["name"];
string sql = string.Format("select name from Users where name='{0}'", name);
SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=Student;User ID=sa;password=123");
conn.Open();
SqlCommand command = new SqlCommand(sql,conn);
SqlDataReader reader = command.ExecuteReader();
try
{
if (reader.Read())
{
Response.Write("ok");//表示存在用户名,不可用使用
}
}
catch (Exception)
{
Response.Write("fail");//不存在,可以使用
}
finally {
conn.Close();
}
Response.End();//
}
}
}