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

如何通过AJAX区分多表单并提交对应数据至数据库?

问题解决:区分多表单提交对应数据

问题根源

你的代码存在两个核心问题:

  • JavaScript的表单提交事件中,变量x未定义,且依赖全局变量获取元素,导致只有最后一次触发changeToInput的记录生效;
  • 所有表单的事件处理操作全局$("form"),会影响页面上所有表单,而非当前提交的那一个。

修改后的JavaScript代码

function changeToInput(x) {
    document.getElementById('result-text-'+x).style.display = 'none';
    const inputEl = document.getElementById('result-'+x);
    inputEl.style.display = 'block';
    inputEl.focus(); // 自动聚焦输入框,提升操作体验
}

$(document).ready(function () {
  $("form").submit(function (event) {
    const $currentForm = $(this); // 锁定当前提交的表单
    $currentForm.find(".form-group").removeClass("has-error");
    $currentForm.find(".help-block").remove();

    // 从当前表单内直接提取数据,无需依赖外部变量
    const formData = {
      runner_id: $currentForm.find('input[name="runner_id"]').val(),
      result: $currentForm.find('input[name="result"]').val(),
    };

    $.ajax({
      type: "POST",
      url: "update_result.php",
      data: formData,
      dataType: "json",
      encode: true,
    }).done(function (data) {
      console.log(data);
      if (data.success) {
        // 仅更新当前表单的内容为成功提示
        $currentForm.html(`<div class="alert alert-success">${data.message}</div>`);
      } else {
        // 错误提示仅添加到当前表单的对应分组
        if (data.errors.runner_id) {
          $currentForm.find("#runner_id-group")
            .addClass("has-error")
            .append(`<div class="help-block">${data.errors.runner_id}</div>`);
        }
        if (data.errors.result) {
          $currentForm.find("#result-group")
            .addClass("has-error")
            .append(`<div class="help-block">${data.errors.result}</div>`);
        }
      }
    }).fail(function () {
        // 失败提示仅显示在当前表单
        $currentForm.html('<div class="alert alert-danger">无法连接服务器,请稍后重试。</div>');
      });

    event.preventDefault();
  });
});

可选PHP优化(适配错误提示)

如果需要错误提示正确显示,给表单内的输入框添加.form-group容器:

echo '<td><form action="update_result.php" method="POST">
<span id="result-text-'.$row['id'].'" ondblclick="changeToInput('.$row['id'].')">kein Ergebnis</span>
<div id="runner_id-group" class="form-group">
<input type="hidden" id="runner_id-'.$row['id'].'" name="runner_id" value="'.$row['id'].'">
</div>
<div id="result-group" class="form-group">
<input id="result-'.$row['id'].'" type="text" name="result" style="display:none">
</div>
<button type="submit" hidden>Save</button></form>';

核心改动说明

  • 锁定当前表单:用$(this)指代触发提交的表单,所有操作仅作用于该表单,避免影响其他记录;
  • 内部获取数据:通过表单内的name属性提取值,彻底摆脱对外部变量的依赖,确保数据对应正确;
  • 局部更新提示:成功/失败提示仅修改当前表单,不会批量影响所有表单。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 16:43:12