功能說明:當使用者在註冊頁面輸入使用者名稱並且滑鼠焦點離開輸入框時,到資料表中去驗證該使用者名稱是否已經存在,如果存在提示【不可用】,否則,提示【可用】。
必備知識:HTML、JavaScript、C#、ADO.NET,另外就是如何建立AJAX請求對象、使用open()和send()方法以及readyState、status、onreadystatechange、responseText的含義和用法。
本例共用到2個頁面:UserReg.aspx—使用者註冊頁面(其實完全可以用靜態頁面)和 CheckUserName.aspx—把輸入的使用者名稱提交到這裡驗證。
UserReg.aspx前台代碼:
Code
1<%@ Page Language="C#" AutoEventWireup="true" CodeFile="UserReg.aspx.cs" Inherits="UserReg" %>
2
3<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4<html xmlns="http://www.w3.org/1999/xhtml">
5<head runat="server">
6 <title>無標題頁</title>
7
8 <script language="javascript" type="text/javascript">
9 <!--
10 function CheckUserName(userName){
11 var xmlhttp;
12 try{
13 xmlhttp = new ActiveXObject('Msxml2.XMLHTTP');
14 }
15 catch(e){
16 try{
17 xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
18 }
19 catch(e){
20 try{
21 xmlhttp = new XMLHttpRequest();
22 }
23 catch(e)
24 {}
25 }
26 }
27
28 xmlhttp.onreadystatechange=function(){
29 if(xmlhttp.readyState == 4){
30 if(xmlhttp.status == 200){
31 var showMes = document.getElementById("showMes");
32
33 if(xmlhttp.responseText == "1"){
34 showMes.innerHTML="不可用";
35 }
36 else{
37 showMes.innerHTML= "可用";
38 }
39 }
40 }
41
42 }
43 xmlhttp.open("get","CheckUserName.aspx?userName="+escape(userName));
44 xmlhttp.send(null);
45 }
46
47 //-->
48 </script>
49
50</head>
51<body>
52 <form id="form1" runat="server">
53 <div>
54 使用者名稱<asp:TextBox ID="txtUserName" runat="server" onblur="CheckUserName(this.value);"></asp:TextBox>
55 <span id="showMes"></span>
56 <br />
57 密 碼<asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
58 </div>
59 </form>
60</body>
61</html>
62
UserReg.aspx後台代碼:無
CheckUserName.aspx前台代碼(把其他的HTML代碼都清除,只留這一行):
Code
1<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CheckUserName.aspx.cs" Inherits="CheckUserName" %>
2
CheckUserName.aspx後台代碼:
Code
1using System;
2using System.Collections;
3using System.Configuration;
4using System.Data;
5using System.Linq;
6using System.Web;
7using System.Web.Security;
8using System.Web.UI;
9using System.Web.UI.HtmlControls;
10using System.Web.UI.WebControls;
11using System.Web.UI.WebControls.WebParts;
12using System.Xml.Linq;
13using System.Data.SqlClient;
14
15public partial class CheckUserName : System.Web.UI.Page
16{
17 protected void Page_Load(object sender, EventArgs e)
18 {
19 using (SqlConnection conn = new SqlConnection(
20 System.Configuration.ConfigurationManager.AppSettings["ConnStr"]))
21 {
22 SqlCommand cmd = new SqlCommand();
23 cmd.Connection = conn;
24 cmd.CommandText = string.Format(
25 "Select Count(*) From PUsers Where UserName='{0}'",
26 Request.QueryString["userName"]);
27 conn.Open();
28 if (int.Parse(cmd.ExecuteScalar().ToString()) == 1)
29 {
30 Response.Write("1");
31 }
32 else
33 {
34 Response.Write("2");
35 }
36 }
37 }
38}
本文來自CSDN部落格,轉載請標明出處:http://blog.csdn.net/shuilv2000/archive/2009/02/17/3898801.aspx