萬盛學電腦網

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

JavaScript 表單提交後禁用按鈕防重複提交:完整模式與無障礙實作

防止使用者重複點擊提交按鈕是表單處理的基本禮儀。本文提供從簡單禁用到完整載入狀態、無障礙、錯誤恢復、防抖、CSRF 整合的進階模式。

最小可行版(3 行)


生產級完整版:載入狀態、錯誤恢復、無障礙


class FormSubmitGuard {
  constructor(formEl, options = {}) {
    this.form = formEl;
    this.btn = formEl.querySelector('button[type="submit"], input[type="submit"]');
    this.originalContent = this.btn.innerHTML;
    this.originalAriaLabel = this.btn.getAttribute('aria-label');
    this.loadingText = options.loadingText || '處理中...';
    this.loadingAriaLabel = options.loadingAriaLabel || '表單提交中,請稍候';
    this.errorResetDelay = options.errorResetDelay ?? 3000; // ms
    
    this.form.addEventListener('submit', this.handleSubmit.bind(this));
  }

  async handleSubmit(e) {
    // 1. 原生驗證
    if (!this.form.checkValidity()) {
      this.form.reportValidity();
      return;
    }
    
    // 2. 防止重複提交(雙重保險)
    if (this.btn.disabled) { e.preventDefault(); return; }
    
    // 3. 進入載入狀態
    this.setLoading(true);
    
    try {
      // 4. 提交(支援 AJAX 或原生)
      if (this.form.dataset.ajax === 'true') {
        e.preventDefault();
        await this.submitAjax();
      }
      // 原生提交:瀏覽器會導向新頁,無需手動恢復
    } catch (err) {
      // 5. 錯誤時恢復按鈕並提示
      this.setLoading(false);
      this.showError(err.message || '提交失敗,請重試');
      // 可選:自動恢復
      setTimeout(() => this.setLoading(false), this.errorResetDelay);
    }
  }

  async submitAjax() {
    const formData = new FormData(this.form);
    // 附加 CSRF Token(若使用)
    const csrf = document.querySelector('meta[name="csrf-token"]')?.content;
    if (csrf) formData.append('_token', csrf);
    
    const resp = await fetch(this.form.action, {
      method: this.form.method,
      body: formData,
      credentials: 'include',
      headers: { 'X-Requested-With': 'XMLHttpRequest' }
    });
    
    if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
    const result = await resp.json();
    if (!result.success) throw new Error(result.message || '伺服器錯誤');
    
    // 成功導向或顯示訊息
    if (result.redirect) location.href = result.redirect;
    else this.showSuccess(result.message || '提交成功');
  }

  setLoading(loading) {
    this.btn.disabled = loading;
    if (loading) {
      this.btn.innerHTML = ` ${this.loadingText}`;
      this.btn.setAttribute('aria-label', this.loadingAriaLabel);
      this.btn.setAttribute('aria-busy', 'true');
    } else {
      this.btn.innerHTML = this.originalContent;
      this.btn.setAttribute('aria-label', this.originalAriaLabel || '');
      this.btn.removeAttribute('aria-busy');
    }
  }

  showError(msg) {
    this._showMessage(msg, 'error');
  }
  showSuccess(msg) {
    this._showMessage(msg, 'success');
  }
  _showMessage(msg, type) {
    // 簡易 Toast 實作,實際專案建議用成熟庫
    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    toast.setAttribute('role', 'alert');
    toast.textContent = msg;
    document.body.appendChild(toast);
    requestAnimationFrame(() => toast.classList.add('show'));
    setTimeout(() => { toast.classList.remove('show'); setTimeout(() => toast.remove(), 300); }, 3000);
  }
}

// 初始化
document.querySelectorAll('form[data-guard="true"]').forEach(f => new FormSubmitGuard(f));

CSS:Spinner 動畫與 Toast


.spinner {
  display: inline-block; width: 1em; height: 1em; margin-right: 0.5em;
  border: 2px solid currentColor; border-right-color: transparent;
  border-radius: 50%; animation: spin 0.6s linear infinite; vertical-align: -0.125em;
}
@keyframes spin { to { transform: rotate(360deg); } }

.toast {
  position: fixed; bottom: 20px; right: 20px; z-index: 9999;
  padding: 12px 20px; border-radius: 8px; color: #fff;
  background: #333; box-shadow: 0 4px 12px rgba(0,0,0,.2);
  transform: translateY(100px); opacity: 0; transition: all 0.3s ease;
}
.toast.show { transform: translateY(0); opacity: 1; }
.toast-success { background: #27ae60; }
.toast-error { background: #e74c3c; }

進階模式對比

模式適用場景優點缺點
原生提交 + 禁用傳統多頁應用、無 AJAX零 JS 依賴、瀏覽器原生處理無法顯示載入進度、錯誤需後端導向錯誤頁
AJAX + 禁用 + 載入態SPA、局部刷新體驗佳、可顯示進度、錯誤不跳頁需處理 CSRF、重導、歷史狀態
防抖提交(按鈕不禁用)搜尋、自動儲存使用者可連續操作不適用「不可冪等」操作(下單、付款)
一次性 Token(後端生成)高安全表單(付款、刪除)根治重複提交、防 CSRF後端複雜度高、需狀態管理

無障礙檢查清單

  • ✅ 按鈕 disabled 狀態正確切換
  • ✅ aria-busy="true" 標示載入中
  • ✅ aria-label 更新為「處理中...」
  • ✅ Spinner 加 aria-hidden="true" 避免讀出「旋轉」
  • ✅ 錯誤/成功訊息用 role="alert" / aria-live="polite"
  • ✅ 鍵盤可操作(Enter 提交、ESC 關閉 Toast)

結語

「提交後禁用按鈕」不只是 btn.disabled = true,完整方案需包含原生驗證、載入狀態 UI、錯誤自動恢復、AJAX/原生雙模支援、CSRF 整合、無障礙屬性、Toast 回饋。將邏輯封裝為 FormSubmitGuard 類別並掛載於 form[data-guard],即可在專案中零配置複用,並隨時擴充再驗證、檔案上傳進度等功能。

copyright © 萬盛學電腦網 all rights reserved