脚本宝典收集整理的这篇文章主要介绍了Ajax实现异步刷新验证用户名是否已存在的具体方法,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
都是简单的实例,所以直接发代码
静态页面Ajax.htML
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 @R_360_315@ 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后台代码:
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()方法来终止写入,否则可能会发送一个完整页面过去。
以上是脚本宝典为你收集整理的Ajax实现异步刷新验证用户名是否已存在的具体方法全部内容,希望文章能够帮你解决Ajax实现异步刷新验证用户名是否已存在的具体方法所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。