DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> jQuery入門知識 >> JQuery特效代碼 >> jquery學習筆記 用jquery實現無刷新登錄
jquery學習筆記 用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當中,僅僅只是驗證用戶名和密碼是否匹配,驗證碼是否正確。Login.ashx是用C#語言寫的,如果你們學習的是別的語言就將地址更換為別的就可以了。
img.ashx是生成驗證碼的程序,每點擊一次圖片都會重新訪問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