DIV CSS 佈局教程網

jQuery 學習筆記:打造無刷新登入功能
編輯:JQuery特效代碼     

閒聊到此,我們直接進入主題——如何用 jQuery 打造無刷新登入。先來看 HTML 部分的結構:

<table>
<tr>
<td>用戶名:</td>
<td><input type="text" id="username" /></td>
</tr>
<tr>
<td>密碼:</td>
<td><input type="text" id="password" /></td>
</tr>
<tr>
<td>驗證碼:</td>
<td><input type="text" id="cord" /><img alt="點擊更換驗證碼" title="看不清楚,請單擊我!" id="checkcord" src="img.ashx" /></td>
</tr>
<tr>
<td><input type="button" onclick="login();" value="登錄" /></td>
<td></td>
</tr>
</table>

這段結構涵蓋了登入驗證與點擊更換驗證碼兩個功能,本身並無複雜之處。接著是 jQuery 的部分:

<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>(別忘了先引入 jQuery,否則後續程式碼無法運作)
<script type="text/javascript">
// 用 jQuery 實現無刷新的登入驗證
function login() {
$.ajax({
url: 'Login.ashx', // 訪問路徑
data: 'username=' + $("#username").val() + "&password=" + $("#password").val() + "&cord=" + $("#cord").val(), // 需要驗證的參數
type: 'post', // 傳值方式
error: function () { // 訪問失敗時呼叫
alert("鏈接服務器錯誤!");
},
success: function (msg) { // 訪問成功時呼叫,msg 為 Login.ashx 的回傳值
alert(msg);
}
});
}
// 驗證碼圖片
$(function () {
$("#username").focus();
$("#checkcord").click(function () {
$("#checkcord").attr("src", "img.ashx?time=" + new Date());
});
})
</script>

核心程式碼大致如上。當使用者點擊登入按鈕時會觸發 login,透過 jQuery 向 Login.ashx 發出請求。Login.ashx 只負責驗證帳號密碼是否相符、驗證碼是否正確,這裡以 C# 撰寫;若你採用其他語言,只要替換掉請求位址即可。

img.ashx 則是產生驗證碼的程式,每點擊一次圖片就會重新訪問一次,因此圖片會隨之更新。產生圖片時會一併寫入保存驗證碼的 session,Login.ashx 只要比對使用者輸入值與 session 值是否相同即可。以下是主要程式碼:

context.Response.ContentType = "text/plain";
string username = context.Request.Form["username"];
string password = context.Request.Form["password"];
string cord = context.Request.Form["cord"];
if (context.Session["cord"] != null)
{
if (context.Session["cord"].ToString() == cord)
{
if (username == "admin" && password == "admin")
{
context.Response.Write("登錄成功!");
}
else
{
context.Response.Write("登錄失敗!用戶名和密碼錯誤!");
}
}
else
{
context.Response.Write("驗證碼錯誤!");
}
}

以上即為登入判斷的核心邏輯。希望這份筆記對你有所幫助,也歡迎多方指教。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved