ajax用户名注册自动刷新,Ajax实现异步刷新验证用户名是否已存在的具体方法

都是简单的实例,所以直接发代码

静态页面Ajax.html

Ajax

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 = "";

}

ajax

账号:
密码:
确认密码:
姓名:

在账号输入框失去焦点时调用函数

访问服务器使用的是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();

}

///

/// 获取数据库连接

///

///

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();

}

}

}

}

在后台中验证用户名是否已经存在于数据库中,返回真或者假

运行结果:

fd833bc3cf11fd15294688264cc4cd9c.png

数据库很简单,只建了一张表userinfo,有3个字段:account、passwd、name

注意:在后台往请求页面写数据时,当写完要发送的数据之后,需要调用Response.end()方法来终止写入,否则可能会发送一个完整页面过去。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值