一款經(jīng)典的ajax登錄頁(yè)面 后臺(tái)asp.net
實(shí)現(xiàn)過(guò)程
1. 新建一名為login.htm的靜態(tài)網(wǎng)頁(yè)文件,作為登錄頁(yè)面,如圖
body標(biāo)簽代碼,代碼如下:
- <body onkeydown ="enterLogin()">
- <div style="text-align: center">
- <table border="1" cellpadding="1">
- <tr>
- <td align="center" style="width: 100px; height: 20px; background-color: #99cccc"
- valign="middle">
- 用戶名:< span>td>
- <td align="center" style="width: 74px; height: 20px; background-color: #99cccc" valign="middle">
- <input id="txtusername" style="width: 111px; height: 19px" type="text" onblur ="checkuser()" />< span>td>
- <td align="center" style="width: 199px; height: 20px; background-color: #99cccc"
- valign="middle"><img src="" id ="imgCheck" style = "visibility :hidden; "/ ><span id ="unMessage">
- < span>span>< span>td>
- < span>tr>
- <tr>
- <td align="center" style="width: 100px; height: 29px; background-color: #99cccc"
- valign="middle">
- 密碼:< span>td>
- <td align="center" style="width: 74px; height: 29px; background-color: #99cccc" valign="middle">
- <input id="txtpwd" style="width: 107px; height: 17px" type="password" />< span>td>
- <td align="center" style="width: 199px; height: 29px; background-color: #99cccc"
- valign="middle"><span id ="pwdMessage">< span>span>
- < span>td>
- < span>tr>
- <tr>
- <td align="center" colspan="3" style="background-color: #99cccc" valign="middle">
- <input id="cbRememberPwd" type="checkbox" />記住密碼一個(gè)月< span>td>
- < span>tr>
- <tr>
- <td align="center" colspan="3" style="background-color: #99cccc" valign="middle">
- <input id="btnOK" type="button" value="登錄" onclick ="login()" />
- <input id="btnReset" type="button" value="重置" onclick ="reset()" />< span>td>
- < span>tr>
- < span>table>
- < span>div>
- < span>body>
#p#
2. 在login.htm中引入外部js代碼
- <script type ="text/javascript" src ="aj.js" >< span>script>
- <script type ="text/javascript" src ="loginCookies.js" >< span>script>
其中aj.js為ajax封裝的類,loginCookie.js為對(duì)Cookie操作的代碼
aj.js代碼如下:
- //JScript文件
- //ajax請(qǐng)求功能函數(shù)
- //get調(diào)用方式:(1)實(shí)例化 var aj=new ajax(); (2)調(diào)用get函數(shù) aj.get(url,callback) (3)寫回調(diào)函數(shù) function callback(xhr){xhr.responsetext}
- //post調(diào)用方式:(1)實(shí)例化 var aj=new ajax(); (2)調(diào)用post函數(shù) aj.post(url,content,callback) (3)寫回調(diào)函數(shù) function callback(xhr){xhr.responsetext}
- //構(gòu)造ajax對(duì)象
- function ajax()
- {
- function getXHR()//獲取xmlhttprequest
- {
- var request=false;
- try
- {
- request = new XMLHttpRequest();
- }
- catch (trymicrosoft)
- {
- try
- {
- request = new ActiveXObject("Msxml2.XMLHTTP");
- }
- catch (othermicrosoft)
- {
- try
- {
- request = new ActiveXObject("Microsoft.XMLHTTP");
- }
- catch (failed)
- {
- request = false;
- }
- }
- }
- return request;
- }
- this.get = function (openUrl,successFun)//ajax對(duì)象的get方法,通過(guò)get方式發(fā)送請(qǐng)求,openUrl為請(qǐng)求的頁(yè)面,successFun為成功回調(diào)執(zhí)行的函數(shù)
- {
- var request = getXHR();
- request.open("get",openUrl,true);
- // request.onreadystatechange = function ()
- // {
- // if (request.readystate==4)
- // {
- // if (request.status==200)
- // {
- // successFun(request);
- // }
- // }
- // };
- request.onreadystatechange = update;
- function update()
- {
- if (request.readystate==4)
- {
- if (request.status==200)
- {
- successFun(request);
- }
- }
- }
- request.send(null);
- }
- this.post = function (openUrl,sendContent,successFun)//ajax對(duì)象的post方法,通過(guò)post方式發(fā)送請(qǐng)求,openUrl為請(qǐng)求的頁(yè)面,successFun為成功回調(diào)執(zhí)行的函數(shù)
- {
- var request = getXHR();
- request.open("post",openUrl,true);
- request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");//告訴服務(wù)器發(fā)送的是文本
- request.onreadystatechange = update;
- function update()
- {
- if (request.readystate==4)
- {
- if (request.status==200)
- {
- successFun(request);
- }
- }
- }
- request.send(sendContent);
- }
- }
loginCookie.js代碼如下
- //JScript文件
- //SetCookie 保存一個(gè)Cookie。參數(shù)中除了name和value以外,其他可以省略。
- //GetCookie 通過(guò)一個(gè)Cookie的名字取出它的值。
- //DelCookie 刪除一個(gè)Cookie,也就是讓一個(gè)Cookie立刻過(guò)期。參數(shù)中除了name,其他可以省略。
- //測(cè)試
- //SetCookie("username", "123");expires代表"月"
- //alert(GetCookie("username"));
- //DelCookie("username");
- //alert(GetCookie("username"));
- function SetCookie(name, value, expires, path, domain, secure) {
- var today = new Date();
- today.setTime(today.getTime());
- if(expires) { expires *= 2592000; }
- var expires_date = new Date(today.getTime() + (expires));
- document.cookie = name + "=" + escape(value)
- + (expires ? ";expires=" + expires_date.toGMTString() : "")
- + (path ? ";path=" + path : "")
- + (domain ? ";domain=" + domain : "")
- + (secure ? ";secure" : "");
- }
- function GetCookie(name) {
- var cookies = document.cookie.split( ';' );
- var cookie = '';
- for(var i=0; i<cookies.length; i++) {
- cookie = cookies[i].split('=');
- if(cookie[0].replace(/^\s+|\s+$/g, '') == name) {
- return (cookie.length <= 1) ? "" : unescape(cookie[1].replace(/^\s+|\s+$/g, ''));
- }
- }
- return null;
- }
- function Delcookie(name, path, domain) {
- document.cookie = name + "="
- + (path ? ";path=" + path : "")
- + (domain ? ";domain=" + domain : "")
- + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
- }
#p#
3. 寫login.htm頁(yè)面中的js代碼,放在head標(biāo)簽之間
- <script type ="text/javascript" >
- window.onload = function (){
- document.getElementById ('txtusername').focus();//用戶名框獲得焦點(diǎn)
- if (GetCookie('user_name') != null && GetCookie('user_pwd') != null)//設(shè)置記住密碼的登錄頁(yè)面
- {
- document.getElementById ("txtusername").value = GetCookie('user_name');
- document.getElementById ("txtpwd").value = GetCookie('user_pwd');
- }
- }
- String.prototype.Trim = function() //自定義的去除字符串兩邊空格的方法
- {
- return this.replace(/(^\s*)|(\s*$)/g, "");
- }
- function checkuser()//檢驗(yàn)用戶名是否正確
- {
- var img = document.getElementById ("imgCheck")
- img.src="iamges/blue-loading.gif";//設(shè)置圖片及其可見(jiàn)性
- img.style.visibility = "visible";
- var aj = new ajax();//以下為ajax請(qǐng)求
- var username = document.getElementById ("txtusername").value.Trim();
- var url = "login.aspx?uname="+escape(username);
- aj.get(url,callback);
- function callback(obj)
- {
- var response = obj.responsetext;
- var res = response.split('\n');
- if (res[0] == "ok")
- {
- img.src="iamges/icon-info.gif";
- document.getElementById ("unMessage").innerHTML = "用戶名正確";
- }
- else
- {
- img.src="iamges/icon-warning.gif";
- document.getElementById ("unMessage").innerHTML = "用戶名錯(cuò)誤";
- }
- }
- }
- function login()//登錄
- {
- if (document.getElementById ("unMessage").innerText == "用戶名錯(cuò)誤")
- {
- alert("你的用戶名錯(cuò)誤");
- }
- else if (document.getElementById ("txtpwd").value == "")
- {
- alert("請(qǐng)輸入密碼");
- }
- else
- {
- var aj = new ajax();
- var username = document.getElementById ("txtusername").value.Trim();
- var userpwd = document.getElementById ("txtpwd").value;
- var url = "login.aspx?name="+escape(username)+"&pwd="+escape(userpwd);
- aj.get(url,callback);
- function callback(obj)
- {
- var response = obj.responsetext;
- var res = response.split('\n');
- if (res[0] == "ok")
- {
- if (document.getElementById ("cbRememberPwd").checked)
- {
- SetCookie('user_name',username,1);//保存密碼一個(gè)月
- SetCookie('user_pwd',userpwd,1);
- }
- else
- {
- SetCookie('user_name',username);
- SetCookie('user_pwd',userpwd);
- }
- window.open ("loginIndex.htm","_self");
- }
- else
- &p; {
- alert("密碼錯(cuò)誤");
- }
- }
- }
- }
- function reset()//重置
- {
- window.onload();//執(zhí)行窗體登錄事件
- document.getElementById ("txtusername").value="";
- document.getElementById ("txtpwd").value="";
- }
- function enterLogin()
- {
- if (event.keyCode==13) //如果按下的是Enter鍵的話,就執(zhí)行登錄語(yǔ)句
- {
- login();
- }
- }
- < span>script>
#p#
4. 新建一名為login.aspx的頁(yè)面,該頁(yè)面作為ajax請(qǐng)求的頁(yè)面,login.aspx.cs代碼如下
- protected void Page_Load(object sender, EventArgs e)
- {
- OleDbConnection Conn = DBcon.get_con();
- if (Request["uname"] != null)
- {
- string username = Request["uname"].ToString();
- string strSql = "select * from [user] where u_name='" + username + "'";
- Conn.Open();
- OleDbCommand Comd = new OleDbCommand(strSql, Conn);
- OleDbDataReader dr = Comd.ExecuteReader();
- if (dr.Read())
- {
- Response.Write("ok\n");
- }
- else
- {
- Response.Write("fail\n");
- }
- //if (Comd.ExecuteNonQuery() > 0)
- //{
- // Response.Write("存在這個(gè)用戶\n");
- //}
- //else
- //{
- // Response.Write("沒(méi)有此用戶名\n");
- //}
- Conn.Close();
- }
- if (Request["name"] != null && Request["pwd"] != null)
- {
- string name = Request["name"].ToString();
- string pwd = Request["pwd"].ToString();
- string strSql = "select * from [user] where u_name='" + name + "'" + " and u_pwd='" + pwd + "'";
- Conn.Open();
- OleDbCommand Comd = new OleDbCommand(strSql, Conn);
- OleDbDataReader dr = Comd.ExecuteReader();
- if (dr.Read())
- {
- Response.Write("ok\n");
- }
- else
- {
- Response.Write("fail\n");
- }
- }
- }
5. 新建一名為loginIndex.htm的靜態(tài)頁(yè)面,作為用戶登錄之后的首頁(yè)
其body標(biāo)簽代碼如下:
- <body>
- <span id ="username"> < span>span>
- < span>body>
6. 在loginIndex.htm頁(yè)面引入loginCookie.js文件
- <script type ="text/javascript" src ="loginCookies.js" >< span>script>
7. 寫loginIdex.htm頁(yè)面的js代碼,放在head標(biāo)簽之間
- <script type ="text/javascript" >
- window.onload = function ()
- {
- if(GetCookie('user_name')==null || GetCookie('user_pwd')==null)//如果沒(méi)有登錄,而是直接在網(wǎng)頁(yè)中輸入網(wǎng)址的
- {
- alert('你還沒(méi)有登錄!\n返回到登陸頁(yè)面。');
- window.navigate("login.htm");
- }
- else
- {
- var uname = GetCookie('user_name');
- document.getElementById ('username').innerHTML ="歡迎你: " + uname + " <a href='#' onclick = 'off()'>注銷< span>a>";//提供"注銷"按鈕
- }
- }
- function off()//注銷事件
- {
- if (window.confirm("你真要注銷嗎?"))
- {
- Delcookie("user_name");
- Delcookie("user_pwd");
- window.navigate("login.htm");
- }
- }
- < span>script>
#p#
8. 完成并演示
客戶端代碼較多,但是交互性很好,演示如下:
當(dāng)輸入完用戶名,鼠標(biāo)光標(biāo)離開(kāi)用戶名框之后,系統(tǒng)會(huì)快速檢驗(yàn)用戶名是否合法
圖-演示1
圖-演示2
進(jìn)入首頁(yè)后,出現(xiàn)的窗口,帶有當(dāng)前登錄的用戶和注銷按鈕
圖-演示3
當(dāng)用戶點(diǎn)擊注銷按鈕時(shí),會(huì)友情提示你是否真的注銷
圖-演示4
當(dāng)你不是輸入用戶和密碼登陸,也是直接在瀏覽器地址欄中輸入首頁(yè)網(wǎng)址的時(shí)候,系統(tǒng)會(huì)提示你沒(méi)有登錄,并直接返回到登陸頁(yè)面。
圖-演示5
當(dāng)用戶輸入了有效的用戶名和密碼,并要求系統(tǒng)記住密碼,用戶下次進(jìn)入到登錄頁(yè)面時(shí),系統(tǒng)會(huì)把上次記住的用戶名和密碼顯示在輸入框中。。
并且這個(gè)時(shí)候直接在瀏覽器的地址欄中輸入首頁(yè)地址,也是能正常訪問(wèn)的。
圖-演示7
【編輯推薦】