Ajax实现异步刷新验证用户名是否已存在(一)

2014-11-24 02:45:33 · 作者: · 浏览: 5
由于要做一个注册页面,看到许多网站上都是使用Ajax异步刷新验证用户名是否可用的,所以自己也动手做一个小实例
都是简单的实例,所以直接发代码
静态页面Ajax.html
复制代码
1
2
3 Ajax
4 <script type="text/java script">
5 function loadXMLDoc() {
6 if (document.getElementById("account").value == "") {
7 document.getElementById("accDiv").innerHTML = "用户名不能为空";
8 return;
9 }
10 var xmlHttp;
11 if(window.XMLHttpRequest) { // code for IE7+
12 xmlHttp = new XMLHttpRequest();
13 }
14 else { // code for IE5/IE6
15 xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
16 }
17
18 xmlHttp.onreadystatechange = function () {
19 if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
20 //document.getElementById("myDiv").innerHTML=xmlHttp.responseText;
21 if (xmlHttp.responseText == "true") {
22 document.getElementById("accDiv").innerHTML = "用户名不可用";
23 }
24 else {
25 document.getElementById("accDiv").innerHTML = "用户名可用";
26 }
27 }
28 }
29 var a = document.getElementById("account").value;
30 // get
31 xmlHttp.open("GET", "validate.aspx account=" + a + "&random=" + Math.random, true);
32 xmlHttp.send();
33 }
34 function delData() {
35 document.getElementById("account").value = "";
36 document.getElementById("accDiv").innerHTML = "";
37 }
38
39
40
41

ajax

42
43
44
45
46
47
48
49
50
51
52
53
54
55
账号:
密码:
确认密码:
姓名:
56
57
58
复制代码
在账号输入框失去焦点时调用函数
访问服务器使用的是Get方法,所以在参数处使用了附加随机码来避免缓存。
验证页面validate.aspx后台代码:
复制代码
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Web;
5 using System.Web.UI;
6 using System.Web.UI.WebControls;
7 using System.Configuration;
8 using System.Data.Sql;
9 using System.Data.SqlClient;
10
11 public partial class Ajax_validate_validate : System.Web.UI.Page
12 {
13 public SqlConnection conn;
14
15 protected void Page_Load(object sender, EventArgs e)
16 {
17 Response.Clear();
18 if (Exists(Request.QueryString["account"]))
19 Response.Write("true");
20 else
21 Response.Write("false");
22 Response.End();
23 }
24 ///
25 /// 获取 数据库连接
26 ///
27 ///
28 protected SqlConnection GetConnection()
29 {
30 string str = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
31 conn = new SqlConnection(str);
32 return conn;
33 }
34 protected bool Exists(string account)
35 {
36 using (GetConnection())
37 {
38 try
39 {
40 conn.Open();
41 string sqlStr = "select count(*) from userinfo where account='" + account + "'";
42 SqlCommand cmd = new SqlCommand(sqlStr, conn);
43 int row = Convert.ToInt32(cmd.ExecuteScalar()