使用 VS2010 開發 ASP.NET WebForms 頁面,需將登錄框(用戶名/密碼)的值通過 jQuery AJAX 傳遞至後端 .aspx.cs 驗證,成功則登錄,失敗則提示錯誤。
.aspx): 給輸入框設置 id(如 txtUser, txtPwd),按鈕類型設為 button 避免表單自動提交。$("#btnLogin").click(function() {
var user = $("#txtUser").val();
var pwd = $("#txtPwd").val();
$.ajax({
type: "POST",
url: "Login.aspx/CheckUser", // 靜態 WebMethod
data: JSON.stringify({ username: user, password: pwd }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
if (response.d) {
window.location.href = "Main.aspx"; // 登錄成功跳轉
} else {
alert("用戶名或密碼錯誤");
}
},
error: function(xhr) { alert("請求異常: " + xhr.status); }
});
});
Login.aspx.cs):
[System.Web.Services.WebMethod]
public static bool CheckUser(string username, string password) {
// 這裡驗證邏輯:查數據庫、比對哈希等
return username == "admin" && password == "123456"; // 示例
}
public static,標註 [WebMethod]。data 中的 JSON 鍵名一致(區分大小寫)。response.d 獲取(ASP.NET AJAX 特有包裝)。bcrypt/PBKDF2 後端驗證哈希,切勿明文傳輸/存儲。HttpContext.Current.Session: 靜態 WebMethod 中需通過 HttpContext.Current.Session 讀寫 Session。