PHP中不使用Input标签如何通过POST向其他页面传值?尝试失败求助
解决PHP中不使用Input标签通过POST传递值的问题
嘿,我看你现在的核心问题很清楚:点击<a>标签时直接走了GET跳转,完全没触发外层表单的POST提交,而且你还希望不用Input标签来传递数据。下面给你几个实用的解决方案:
方案1:用JavaScript手动发起POST请求(无Input标签)
我们可以给链接绑定点击事件,阻止它默认的GET跳转,然后用JavaScript创建POST请求把id传过去,全程不用写任何<input>标签。
先修改你循环里的代码,把链接改成带data-id属性的样式:
while ($row = $result->fetch_assoc()) { $id = $row["id"]; // 用data-id存储要传递的id,给链接加个类方便JS定位 echo "<a href='#' class='post-trigger' data-id='{$id}'>" . fullname($row['firstname'], $row['lastname']) . "</a><br>"; }
然后在页面末尾加一段JavaScript代码来处理点击事件:
// 找到所有带post-trigger类的链接 document.querySelectorAll('.post-trigger').forEach(link => { link.addEventListener('click', function(e) { e.preventDefault(); // 阻止默认的GET跳转行为 const targetId = this.dataset.id; // 获取存储的id // 用FormData来构建POST数据 const formData = new FormData(); formData.append('id', targetId); // 发送POST请求并跳转到目标页面 fetch('details.php', { method: 'POST', body: formData }).then(() => { window.location.href = 'details.php'; }).catch(err => { console.error('提交出错:', err); }); }); });
这样处理后,点击链接就会通过POST把id传到details.php,你在目标页面用$_POST['id']就能拿到值,而且全程没用到Input标签。
方案2:把链接改成样式化的提交按钮(无额外Input标签)
如果你不想用太多JS,也可以把链接换成表单的提交按钮,然后用CSS把按钮改成链接的样子,再通过JS在提交时把id加进去。
修改循环里的代码:
while ($row = $result->fetch_assoc()) { $id = $row["id"]; // 创建表单,用data-id存id echo "<form action='details.php' method='POST' class='id-form' data-id='{$id}'>"; // 把按钮样式改成链接的样子 echo "<button type='submit' class='link-style-btn'>" . fullname($row['firstname'], $row['lastname']) . "</button><br>"; echo "</form>"; }
添加CSS让按钮看起来和链接一样:
.link-style-btn { background: transparent; border: none; color: #0066cc; text-decoration: underline; cursor: pointer; padding: 0; font-size: inherit; } .link-style-btn:hover { color: #004499; }
再添加一段JS处理表单提交:
document.querySelectorAll('.id-form').forEach(form => { form.addEventListener('submit', function(e) { e.preventDefault(); const formData = new FormData(this); formData.append('id', this.dataset.id); // 把id加到POST数据里 fetch(this.action, { method: this.method, body: formData }).then(() => { window.location.href = this.action; }); }); });
点击这个“链接式按钮”就会触发POST提交,同样不需要Input标签。
为什么你原来的代码没效果?
你原来的代码里,<a>标签是独立的跳转元素,和包裹它的表单没有任何交互关系——点击链接只会直接发起GET请求跳转到details.php,根本不会触发表单的POST提交逻辑,所以表单里的hidden Input也完全没被发送出去。
内容的提问来源于stack exchange,提问作者Momen
相关产品推荐
相关产品推荐

