首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

VS2010 + jQuery + ASP.NET:前端傳值至後端驗證登錄

     編輯:程式設計疑難解答

場景

使用 VS2010 開發 ASP.NET WebForms 頁面,需將登錄框(用戶名/密碼)的值通過 jQuery AJAX 傳遞至後端 .aspx.cs 驗證,成功則登錄,失敗則提示錯誤。

核心步驟

  1. 前端頁面 (.aspx): 給輸入框設置 id(如 txtUser, txtPwd),按鈕類型設為 button 避免表單自動提交。
  2. jQuery AJAX 請求:
    $("#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); }
        });
    });
    
  3. 後端 WebMethod (Login.aspx.cs):
    [System.Web.Services.WebMethod]
    public static bool CheckUser(string username, string password) {
        // 這裡驗證邏輯:查數據庫、比對哈希等
        return username == "admin" && password == "123456"; // 示例
    }
    
    • 方法必須 public static,標註 [WebMethod]。
    • 參數名需與 AJAX data 中的 JSON 鍵名一致(區分大小寫)。
    • 返回類型自動序列化為 JSON,前端通過 response.d 獲取(ASP.NET AJAX 特有包裝)。

進階建議

  • 密碼加密: 前端用 HTTPS,或配合 bcrypt/PBKDF2 後端驗證哈希,切勿明文傳輸/存儲。
  • 防暴力破解: 後端記錄失敗次數,超限鎖定 IP/賬號。
  • 使用 HttpContext.Current.Session: 靜態 WebMethod 中需通過 HttpContext.Current.Session 讀寫 Session。

參考資源

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved