萬盛學電腦網

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

JavaScript 動態創建 Form 表單並提交(支援多種輸入類型)

應用場景

  • 需在特定條件下向不同 URL 提交數據(如多支付通道跳轉)。
  • 需攜帶非表單內的數據提交。
  • 避開瀏覽器攔截 window.open 的 POST 彈窗限制。

核心代碼:通用動態表單提交函數

/**
 * 動態創建並提交表單
 * @param {Object} options
 *   - action: 提交地址
 *   - method: 'post' | 'get' (默認 post)
 *   - target: '_blank' | '_self' | iframe name (可選)
 *   - data: { key: value } 或 { key: {value, type} } type 可為 'hidden', 'text', 'checkbox' 等
 *   - onSubmitted: 可選回調
 */
function submitForm(options) {
  var form = document.createElement('form');
  form.method = options.method || 'post';
  form.action = options.action;
  if (options.target) form.target = options.target;
  form.style.display = 'none';

  // 添加字段
  for (var key in options.data) {
    if (!options.data.hasOwnProperty(key)) continue;
    var val = options.data[key];
    var input = document.createElement('input');
    input.name = key;
    // 支援傳入 {value: 'x', type: 'checkbox'} 格式
    if (val && typeof val === 'object' && val.value !== undefined) {
      input.value = val.value;
      input.type = val.type || 'hidden';
      if (input.type === 'checkbox') input.checked = !!val.value;
    } else {
      input.type = 'hidden';
      input.value = val;
    }
    form.appendChild(input);
  }

  document.body.appendChild(form);
  form.submit();
  document.body.removeChild(form); // 提交後移除

  if (options.onSubmitted) options.onSubmitted();
}

使用示例

基本 POST 跳轉

submitForm({
  action: '/pay/gateway',
  data: {
    orderId: '20231001001',
    amount: 99.90,
    channel: 'alipay'
  }
});

新標籤頁打開 (target="_blank")

submitForm({
  action: '/report/export',
  target: '_blank',
  data: { reportId: 'RPT_001', format: 'excel' }
});

複雜字段類型

submitForm({
  action: '/api/submit',
  data: {
    username: 'zhangsan',
    agreeTerms: { value: true, type: 'checkbox' }, // 會生成 checked checkbox
    bio: { value: '開發者', type: 'text' } // 可見文本框 (罕見需求)
  }
});

原文代碼優化要點

  1. 封裝通用函數:原文代碼硬編碼字段名、獲取值邏輯耦合,改為配置化。
  2. 自動清理:form.submit() 後移除 form,避免 DOM 污染。
  3. 支援 target:可指定 _blank、iframe name 等。
  4. 類型擴展:允許指定 type,兼容 checkbox 等特殊類型。
  5. 無 jQuery 依賴:原生 DOM API,輕量無依賴。

注意事項

  • form.submit() **不觸發** onsubmit 事件驗證,若需驗證請手動調用或改用 form.requestSubmit() (現代瀏覽器)。
  • 跨域提交需後端配置 CORS 或使用 iframe 代理。
  • 大量數據建議改用 AJAX + Blob 下載或分片上傳。
copyright © 萬盛學電腦網 all rights reserved