本文讲解如何在包含多个相似表单的页面中,使用 jquery 精准获取每个表单的独立数据并发送 ajax 请求,避免因重复 id 导致仅第一个表单生效的问题。核心方案是用 `$(this).find()` 定位当前提交表单内的元素。
在动态渲染多条内容(如卡片列表)的页面中,为每条记录嵌入独立编辑表单是一种常见需求。但若所有表单都使用相同 id(例如
HTML 规范明确要求 id 属性必须全局唯一,因此解决方案的第一步是:移除所有重复的 id,改用 name 属性配合类选择器进行上下文定位。
selectToplu('contents_temp');
foreach ($query as $row) { ?>
@@##@@">
x
⚠️ 注意事项:使用 htmlspecialchars() 输出 PHP 变量,防止 XSS 攻击;所有 添加 class="form" 作为统一委托目标;状态提示区改为 ,避免 ID 冲突;移除 onclick="buton();" 等冗余内联事件,交由 jQuery 统一管理。
$(document).ready(function() {
// 监听所有 .form 的 submit 事件(非 click!)
$('.form').on('submit', function(e) {
e.preventDefault(); // 阻止默认表单提交
// ✨ 关键:使用 $(this) 指向当前被提交的表单,再 find 其内部字段
const $form = $(this);
const text = $form.find('[name="text"]').val().trim();
const id = $form.find('[name="id"]').val();
const $status = $form.find('.status');
// 简单校验
if (!text || !id) {
$status.html('Lütfen tüm alanları doldurun.').removeClass('text-success').addClass('text-danger').show();
return;
}
// 发送 AJAX 请求
$.post('../../app/modules/content/update.php', {
text: text,
id: id
}, function(response) {
$status.html('Güncellendi ✓').removeClass('text-danger').addClass('text-success').show();
// 可选:3秒后自动隐藏提示
setTimeout(() => $status.fadeOut(300), 3000);
}).fail(function() {
$status.html('Hata oluştu! Lütfen tekrar deneyin.').removeClass('text-success').addClass('text-danger').show();
});
});
});通过以上重构,每个卡片的表单都能独立、准确地
提交自身数据,真正实现“一页面多数据并行更新”。