You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Web应用表单重复提交致崩溃,求单次提交解决方案

解决表单重复提交导致的崩溃问题

你的问题核心是表单被提交了两次:一次是你通过AJAX手动发起的请求,另一次是浏览器对<button>的默认表单提交行为,再加上服务端可能重复注册了路由,多重作用下导致了应用崩溃。下面是具体的修复方案:


1. 阻止按钮的默认表单提交行为

你的按钮没有指定type属性,浏览器会默认把它当作type="submit"按钮——点击时不仅会执行onclick里的sendForm(),还会触发表单的默认提交(刷新页面或再次发送POST请求到表单的action地址)。

修复方式二选一:

  • 给按钮添加type="button":

    <button id="button" class="btn btn-primary btn-lg" onclick="sendForm()" type="button" value="GENERA XML">GENERA XML</button>
    

    这样按钮就只会执行你写的sendForm()函数,不会触发表单的默认提交逻辑。

  • 在sendForm函数里阻止默认事件:
    修改JS函数,接收事件参数并调用preventDefault():

    function sendForm(event) {
      // 阻止浏览器默认的表单提交行为
      event.preventDefault();
      
      const Form = document.querySelector('.broadcast-form');
      let formSend = new FormData();
      // ... 你的其他表单数据组装代码
    }
    

    同时按钮的onclick要传递事件参数:

    <button id="button" class="btn btn-primary btn-lg" onclick="sendForm(event)" value="GENERA XML">GENERA XML</button>
    

2. 合并服务端重复的路由注册

从你提供的代码来看,服务端有两个app.post('/form')的路由注册:

// 第一个路由
app.post('/form', (req, res) => { ... })

// 第二个带upload中间件的路由
app.post('/form', upload.single('fileVideo'),(req, res) => { ... })

Express会按顺序执行所有匹配的路由处理函数,这会导致同一个请求被两次处理,也是崩溃的潜在原因。你需要合并这两个路由,把中间件加到同一个处理函数上:

// 合并后的路由
app.post('/form', upload.single('fileVideo'), (req, res) => {
  var date = new Date(), blockid = (date.toJSON().replace(/[\-T:.Z]/g, ''));
  cliente = req.body.cliente;
  inputFile = req.body.inputFile;
  // ... 你的其他数据库操作逻辑
})

3. 额外的防重复提交优化(可选)

为了彻底避免用户重复点击导致的问题,还可以在按钮点击后暂时禁用它,直到请求完成:

function sendForm(event) {
  event.preventDefault();
  const button = document.getElementById('button');
  // 禁用按钮,防止重复点击
  button.disabled = true;
  
  const Form = document.querySelector('.broadcast-form');
  let formSend = new FormData();
  // ... 你的表单数据组装代码
  
  $.ajax({
    url: '/form',
    method: "POST",
    dataType: 'json',
    data: formSend,
    processData: false,
    contentType: false,
    success: function(result){
      console.log(result);
      // 请求成功后恢复按钮(可选)
      button.disabled = false;
    },
    error: function(er){
      console.log(er);
      // 请求失败也恢复按钮,方便用户重试
      button.disabled = false;
    }
  });
}

这样就能确保表单只会被提交一次,解决崩溃问题啦!

内容的提问来源于stack exchange,提问作者Gargantua

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:34:57