AJAX实现即时用户名的验证
刚开始接触AJAX,希望高手帮忙!谢谢....
代码如下:
<script type ="text/javascript" language="javascript">
var xmlHttp;
function createXMLHttpRequest() //创建XMLHttpRequest对象
{
if (window.ActiveXObject)
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest)
{
xmlHttp = new XMLHttpRequest();
}
}
function callServer()
{
createXMLHttpRequest();
var username=document.getElementById("txtusername").value;
if((username==null)||(username=="")) return;
var url="checkname.aspx?name="+escape(username);
xmlHttp.onreadystatechange = updatePage;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function updatePage()
{
if (xmlHttp.readyState<4) //表示请求状态还没有成功
{
test1.innerHTML="loading....";
}
if(xmlHttp.readyState == 4) //请求状态为4表示成功
{
if(xmlHttp.status==200) //表示返回状态是成功的
{
var response = xmlHttp.responseText;
test1.innerHTML=response;
//window.alert(xmlHttp.responseText);
}
}
}
</script>
checkname.aspx.cs 中的代码:
protected void Page_Load(object sender, EventArgs e)
{
int flag=0;
SqlConnection conn = DB.createconnection();
string username=Request["name"];
string sql = "select count(*) from Users where UserName='" + username + "'";
SqlCommand myCommand = new SqlCommand(sql,conn);
myCommand.Connection.Open();
try
{
flag=(int)myCommand.ExecuteScalar();
}
catch(Exception ex)
{
throw new Exception(ex.ToString());
}
finally
{
myCommand.Connection.Close();
}
if (flag == 1)
{
Response.Write("非常抱歉!!该用户名已经存在!!");
}
else
{
Response.Write("恭喜您!!该用户名可以注册!!");
}
}
这样怎么实现不了?还有xmlHttp.responseText 如何获得获得验证后的值的?Response.Write这样就可以了吗?谢谢...