Ajax实现异步刷新验证用户名是否已存在的具体方法
都是简单的实例,所以直接发代码
静态页面ajax.html
<html>
<head>
<title>ajax</title>
<script type="text/javascript">
function loadxmldoc() {
if (document.getelementbyid("account").value == "") {
document.getelementbyid("accdiv").innerhtml = "用户名不能为空";
return;
}
var xmlhttp;
if(window.xmlhttprequest) { // code for ie7+
xmlhttp = new xmlhttprequest();
}
else { // code for ie5/ie6
xmlhttp = new activexobject("microsoft.xmlhttp");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readystate == 4 && xmlhttp.status == 200) {
//document.getelementbyid("mydiv").innerhtml=xmlhttp.responsetext;
if (xmlhttp.responsetext == "true") {
document.getelementbyid("accdiv").innerhtml = "用户名不可用";
}
else {
document.getelementbyid("accdiv").innerhtml = "用户名可用";
}
}
}
var a = document.getelementbyid("account").value;
// get
xmlhttp.open("get", "validate.aspx?account=" + a + "&random=" + math.random, true);
xmlhttp.send();
}
function deldata() {
document.getelementbyid("account").value = "";
document.getelementbyid("accdiv").innerhtml = "";
}
</script>
</head>
<body>
<h3>ajax</h3>
<table>
<tr>
<td>账号:</td><td><input id="account" type="text" onblur="loadxmldoc();" onfocus="deldata();"/></td><td><div id="accdiv"></div></td>
</tr>
<tr>
<td>密码:</td><td><input id="passwd" type="password" /></td>
</tr>
<tr>
<td>确认密码:</td><td><input id="vpasswd" type="password" /></td>
</tr>
<tr>
<td>姓名:</td><td><input id="name" type="text" /></td>
</tr>
</table>
</body>
</html>
在账号输入框失去焦点时调用函数
访问服务器使用的是get方法,所以在参数处使用了附加随机码来避免缓存。
验证页面validate.aspx后台代码:
using system;
using system.collections.generic;
using system.linq;
using system.web;
using system.web.ui;
using system.web.ui.webcontrols;
using system.configuration;
using system.data.sql;
using system.data.sqlclient;
public partial class ajax_validate_validate : system.web.ui.page
{
public sqlconnection conn;
protected void page_load(object sender, eventargs e)
{
response.clear();
if (exists(request.querystring["account"]))
response.write("true");
else
response.write("false");
response.end();
}
/// <summary>
/// 获取数据库连接
/// </summary>
/// <returns></returns>
protected sqlconnection getconnection()
{
string str = configurationmanager.connectionstrings["connectionstring"].connectionstring;
conn = new sqlconnection(str);
return conn;
}
protected bool exists(string account)
{
using (getconnection())
{
try
{
conn.open();
string sqlstr = "select count(*) from userinfo where account='" + account + "'";
sqlcommand cmd = new sqlcommand(sqlstr, conn);
int row = convert.toint32(cmd.executescalar());
if (row > 0)
return true;
else
return false;
}
catch (exception e)
{
throw e;
}
finally
{
conn.close();
}
}
}
}
在后台中验证用户名是否已经存在于数据库中,返回真或者假
运行结果:
数据库很简单,只建了一张表userinfo,有3个字段:account、passwd、name
注意:在后台往请求页面写数据时,当写完要发送的数据之后,需要调用response.end()方法来终止写入,否则可能会发送一个完整页面过去。