萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery + AJAX + C# 實現無刷新操作數據庫數據(增刪改查完整案例)

架構概覽

  • 前端:jQuery `$.ajax` / `$.post` / `.load()` 發起異步請求,處理響應更新 DOM。
  • 後端:ASP.NET WebForms (`.aspx`),通過 `Request.Form` / `Request.QueryString` 獲取參數,調用業務邏輯層 (BLL) 操作數據庫,輸出 HTML 片段或 JSON。
  • 核心思想:異步請求避免頁面整體刷新,提升用戶體驗;`stop` 鎖防止並發;loading 圖提升感知性能。

1. 頁面結構與加載邏輯

<div id="comment">
    <img src="images/Wait.gif" title="數據載入中..." />
</div>

<script>
function getInfo() {
    $.ajax({
        url: "doAction.aspx?fig=reader&id=1&page=1",
        type: "POST",
        success: function(data) {
            $("#comment").html(data); // 或 arguments[0]
        },
        error: function() { alert("程序出錯"); }
    });
}

// 簡寫版:$.post
function getInfo1() {
    $.post("doAction.aspx", { fig: "reader", id: "1", page: "1" }, function(data) {
        $("#comment").html(data);
    });
}

// .load 版:一行搞定
$("#content").load("doAction.aspx", { fig: "reader", id: "1", page: "1" }, function(response, status, xhr) {
    if (status === "error") console.error("Load failed");
});
</script>

2. 後端路由分發

// doAction.aspx.cs Page_Load
if (Request.Form["fig"] != null && Request.Form["fig"] == "reader") {
    AjaxGetComment("1", 1);
}

// 業務方法
private void AjaxGetComment(string id, int page) {
    using (CommentBO cm = new CommentBO(id, page - 1)) {
        Response.Write(cm.GetCommentContent()); // 輸出 HTML 片段
    }
    Response.End(); // 關鍵:結束響應
}

3. 新增評論(含驗證碼、防重複提交)

function addComment(parentId) {
    var user = $.trim($('#CommentUser').val());
    var text = $.trim($('#CommentText').val());
    var code = $.trim($('#CommentValidate').val());

    if (!user) { alert('請填寫昵稱'); $('#CommentUser').focus(); return false; }
    if (!text) { alert('請填寫內容'); $('#CommentText').focus(); return false; }
    if (!code) { alert('請輸入驗證碼'); $('#CommentValidate').focus(); return false; }

    disableButton('CommentSubmit', 10); // 10秒倒計時禁用按鈕

    $.ajax({
        url: "doAction.aspx?action=add&commentparentid=" + parentId +
             "&commentuser=" + escape(user) +
             "&commenttext=" + escape(text) +
             "&commentvalidate=" + escape(code) +
             "&time=" + new Date().getTime(), // 防緩存
        type: "GET",
        success: function(data) {
            if (data == "ERROR") {
                alert("驗證碼超時,請重新輸入");
            } else {
                getInfo(); // 刷新列表
                $('#CommentText').val('');
                // 刷新驗證碼圖片
                $('#CommentValidateImages').attr('src', 'VerifyCode.aspx?s=' + Math.random());
                $('#alertMessgae').html(data); // 顯示成功提示
            }
            $('#CommentValidate').val('');
        }
    });
}

// 按鈕倒計時禁用
function disableButton(btnId, seconds) {
    var btn = document.getElementById(btnId);
    btn.disabled = true;
    btn.value = "提交(" + seconds + ")";
    var timer = setInterval(function() {
        seconds--;
        if (seconds > 0) btn.value = "提交(" + seconds + ")";
        else {
            clearInterval(timer);
            btn.disabled = false;
            btn.value = "提交";
        }
    }, 1000);
}

4. 後端新增處理

if (Request.QueryString["action"] == "add") {
    string code = Request.QueryString["commentvalidate"];
    if (Session["VerifyCode"].ToString().ToLower() != code.ToLower()) {
        Response.Write("ERROR");
    } else {
        // 參數獲取(已 escape,服務端需 unescape 或 HttpUtility.UrlDecode)
        string parentId = Request.QueryString["commentparentid"];
        string user = HttpUtility.UrlDecode(Request.QueryString["commentuser"]);
        string text = HttpUtility.UrlDecode(Request.QueryString["commenttext"]);
        string ip = Request.ServerVariables["REMOTE_ADDR"];

        // 參數化查詢防注入(示例為拼接,實際必須用參數化)
        string sql = "INSERT INTO comment (commentparentid, commentuser, commenttext, commentreply, commentip) " +
                     "VALUES (@pid, @user, @text, '', @ip)";
        // DBQuery.ExecuteScalar(sql, parameters...);

        Response.Write("<script>alert('評論發表成功!')</script>");
    }
}

5. 關鍵最佳實踐總結

  • 參數傳遞:`$.post` 用對象自動編碼,`$.ajax` 的 `data` 可傳對象或字符串;GET 請求參數在 URL 中需 `encodeURIComponent`。
  • 防重複提交:前端按鈕倒計時禁用 + 後端 Token/Session 驗證雙重保障。
  • 錯誤處理:`error` 回調捕獲網絡/HTTP 錯誤;業務邏輯錯誤(如驗證碼錯誤)約定返回特定標識(`ERROR`)由 `success` 內判斷。
  • 數據格式:新項目**強烈建議返回 JSON**,前端模板渲染,而非拼接 HTML 字符串返回。
  • 安全:SQL 參數化、XSS 轉義 (`HttpUtility.HtmlEncode`)、CSRF Token、驗證碼、權限校驗。
  • 用戶體驗:Loading 狀態、樂觀 UI(先更新界面再請求)、錯誤友好提示、無限滾動分頁。

現代化遷移建議

  • 後端遷移至 ASP.NET Core Web API / Minimal API,返回標準 JSON。
  • 前端遷移至 Vue/React/Angular + Axios/Fetch,組件化管理狀態。
  • 引入 TypeScript 增強類型安全。
  • 使用 Swagger/OpenAPI 文檔化接口。
copyright © 萬盛學電腦網 all rights reserved