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

在PHP while循环中实现按钮提交不同表单数据的问题

解决PHP循环中表单提交数据重复的问题

问题根源很明确:

  1. 循环里的表单、输入框、按钮都用了重复的id(foo、unq、subm),HTML里id必须唯一,浏览器只会识别第一个匹配的元素。
  2. JS里用document.getElementById("unq")获取值,不管点哪个按钮,只会拿到第一个id为unq的输入框内容。

修正步骤:

1. 修改PHP循环中的HTML代码(去掉重复id,保留必要标识)

<?php
if ($query->num_rows > 0) {
    while ($row12 = $query->fetch_assoc()) {
?>
<form class="yatis" method="POST">
    <div class="flex items-center justify-between">
        <span class="text-sm font-semibold text-black dark:text-black">
            <?php echo $row12["sched2"]; ?>
        </span>
        <!-- 去掉重复id,只保留name属性 -->
        <input type="hidden" name="unq" value="<?php echo $row["unique_id"]; ?>">
        <!-- 去掉重复id,保留class作为选择器 -->
        <button type="submit" name="submit" class="eut px-3 py-1 text-sm font-bold text-gray-100 transition-colors duration-300 transform bg-gray-600 rounded cursor-pointer hover:bg-gray-500">Enroll</button>                
    </div>
</form>
<?php }} else {
    echo 'No records found...';
}
?>

2. 修正JS代码(通过按钮关联对应表单的输入值)

var submit1 = document.querySelectorAll(".eut");
for (let i = 0; i < submit1.length; i++) {
    submit1[i].addEventListener("click", function(e) {
        e.preventDefault();
        // 找到当前按钮所在的表单
        const form = this.closest('.yatis');
        // 在当前表单内获取对应的hidden输入值
        const s1 = form.querySelector('input[name="unq"]').value;
        
        var formData = new FormData();
        formData.append("us1", s1);
        var url = "enroll.php";
        
        // 修正headers里的引号闭合问题
        axios.post(url, formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        })
        // 可添加请求结果提示
        .then(response => {
            console.log(response.data);
        })
        .catch(error => {
            console.error(error);
        });
    });
}

关键说明:

  • 用this.closest('.yatis')获取点击按钮所在的表单,确保只操作当前表单内的元素。
  • 用form.querySelector('input[name="unq"]')在当前表单范围内查找输入框,避免拿到其他表单的数据。
  • 去掉所有重复的id,HTML中id是唯一标识,重复会导致DOM选择器失效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 09:10:44