萬盛學電腦網

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

JavaScript 防止表單重複提交:旗標鎖定與 UI 回饋完整實作

核心原理

使用全域旗標變數 inprocess 鎖定提交狀態,配合按鈕 disabled 屬性與訊息提示,防止使用者重複點擊送出按鈕造成重複請求。

完整實作代碼

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>防止重複表單提交</title>
    <style>
        #refresh {
            display: none;
            width: 200px;
            height: 20px;
            background-color: #ff0;
        }
    </style>
    <script>
        var inprocess = false;
        
        window.onload = function() {
            document.forms["picker"].onsubmit = validateSubmit;
            document.getElementById("refresh").onclick = startOver;
        };
        
        // 提交驗證與鎖定
        function validateSubmit() {
            // 1. 檢查是否已在處理中
            if (inprocess) return false;
            
            // 2. 設定鎖定旗標
            inprocess = true;
            console.log("處理中狀態:", inprocess);
            
            // 3. 禁用送出按鈕
            document.getElementById("submitbutton").disabled = true;
            
            // 4. 顯示「重新開始」按鈕
            document.getElementById("refresh").style.display = "block";
            
            // 5. 顯示處理中訊息
            document.getElementById("message").innerHTML = "<p>正在處理中,請稍候...</p>";
            
            // 6. 回傳 false 阻止表單預設提交(這裡示範用,實際應改為 AJAX 提交)
            return false;
        }
        
        // 重置表單狀態
        function startOver() {
            inprocess = false;
            document.getElementById("submitbutton").disabled = false;
            document.getElementById("message").innerHTML = "";
            document.getElementById("refresh").style.display = "none";
        }
    </script>
</head>
<body>
    <form id="picker" method="post" action="">
        group1:<input type="radio" name="group1" value="one" />
        group2:<input type="radio" name="group1" value="two" />
        group3:<input type="radio" name="group1" value="three" /><br><br>
        Input 1: <input type="text" id="intext" />
        Input 2: <input type="text" id="intext2" />
        Input 3: <input type="text" id="intext3" />
        <input type="submit" id="submitbutton" value="send form" />
    </form>
    <div id="refresh"><p>點我重新開始</p></div>
    <div id="message"></div>
</body>
</html>

進階實作:AJAX 提交版本

function validateSubmit() {
    if (inprocess) return false;
    inprocess = true;
    
    var $btn = $("#submitbutton").prop("disabled", true);
    $("#refresh").show();
    $("#message").html("<p>正在提交資料...</p>");
    
    $.ajax({
        url: "/api/submit",
        type: "POST",
        data: $("#picker").serialize(),
        success: function(res) {
            $("#message").html("<p class='success'>提交成功!</p>");
        },
        error: function(xhr) {
            $("#message").html("<p class='error'>提交失敗:" + xhr.responseText + "</p>");
            // 失敗時解鎖,允許重試
            inprocess = false;
            $btn.prop("disabled", false);
            $("#refresh").hide();
        }
    });
    
    return false; // 阻止傳統表單提交
}

多重防護策略(生產環境建議)

層級方案說明
前端 UI按鈕 disabled + 旗標鎖定即時回饋,防止手抖雙擊
前端 路由單頁應用路由守衛防止重複導航觸發提交
前端 儲存sessionStorage 記錄提交狀態頁面刷新/跳轉後仍可攔截
後端 API冪等性 Key(Idempotency Key)同一請求 ID 只處理一次,根治重複
資料庫唯一索引 / 悲觀鎖資料層面最終防線

冪等性 Key 實作範例(後端)

// 前端產生唯一請求 ID
var requestId = "req_" + Date.now() + "_" + Math.random().toString(36).substr(2, 9);

// 送出時攜帶 Header
$.ajax({
    headers: { "Idempotency-Key": requestId },
    // ...
});

// 後端(Node.js/Express 範例)
app.post('/api/submit', function(req, res) {
    var key = req.headers['idempotency-key'];
    if (redis.setnx(key, 1)) { // 原子性設定,僅首次成功
        redis.expire(key, 86400); // 24小時過期
        // 執行業務邏輯...
        res.json({ success: true });
    } else {
        res.status(409).json({ error: "重複請求" });
    }
});

總結

前端旗標鎖定是基礎防護,解決大多數誤操作。關鍵業務務必結合後端冪等性設計,才能從根本上杜絕重複提交導致的資料不一致問題。

copyright © 萬盛學電腦網 all rights reserved