Ajax无刷新验证用户名是否被注册了
DOM版,此代码仅支持IE浏览器
<!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>
<script type="text/javascript">
function checkUser() {
var text1 = document.getElementById("Text1").value;
if(text1!=""){
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
if(!xmlhttp){
alert("ajax错误");
return false;
}
xmlhttp.open("POST", "CheckUserName.ashx?username=" + text1 + "&t=" + new Date(), "false");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
// alert(xmlhttp.responseText);
if (xmlhttp.responseText == "ok") {
document.getElementById("sp1").innerHTML = "<font color=green>恭喜用户名'" + text1 + "'可以使用</font>";
}
else if (xmlhttp.responseText == "error") {
document.getElementById("sp1").innerHTML = "<font color=red>用户名'" + text1 + "'已经被注册了</font>";
}
else {
alert("ajax返回错误");
}
}
else {
alert("ajax服务器返回错误");
}
}
}
xmlhttp.send();
}
}
</script>
</head>
<body>
用户名:<input id="Text1" type="text" οnblur="return checkUser()" /><span id="sp1"></span>
</body>
</html>
JQuery版,此代码兼容绝大部分浏览器.
<!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>
<script src="../js/jquery-1.4.2.js" type="text/javascript"></script>
<script type="text/javascript">
function checkUser() {
var username = $("#Text1").val();
if (username != "") {
$.post("CheckUserName.ashx", { "username": username }, function(data, status) {//jQuery封装的ajax post方法,第一个参数为post页面,第二个为参数数组,第三个为接受结果匿名函数
if (status == "success") {//返回成功
if (data == "ok") {//值为ok
$("#sp1").html("<font color=green>恭喜用户名'" + username + "'可以使用</font>")
}
else if (data == "error") {//值为error
$("#sp1").html("<font color=red>用户名'" + username + "'已经被注册了</font>")
}
else { alert("return error"); }
}
else { alert("ajax error"); }
});
}
}
</script>
</head>
<body>
用户名:<input id="Text1" type="text" οnblur="return checkUser()" /><span id="sp1"></span>
</body>
</html>
服务器处理程序:CheckUserName.ashx
<%@ WebHandler Language="C#" Class="CheckUserName" %>
using System;
using System.Web;
public class CheckUserName : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
string us=context.Request["username"];
jiang_Db newdb = new jiang_Db();
bool hasname = newdb.ExecSql_Bool("select COUNT(*) from [user] where [user_name]='"+us+"'");
if (hasname)
{
context.Response.Write("error");
}
else
{
context.Response.Write("ok");
}
}
public bool IsReusable {
get {
return false;
}
}
}