You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

如何在修改表单form action的同时传递隐藏文本字段(hidden text field)值

如何在修改表单form action的同时传递隐藏文本字段(hidden text field)值

兄弟,我看你现在的问题是:下拉框选完页面跳转后,隐藏的id字段没传过去对吧?这是因为你当前的goto函数是直接跳页面,根本没走表单提交的流程,隐藏字段自然带不过去啦!

给你两种靠谱的解决办法,你按需选:

方法一:通过表单提交传递(推荐,支持GET/POST)

这个方法是真正利用表单的提交机制,把隐藏字段一起发过去,步骤很简单:

  1. 先给你的表单补个method属性(选GET还是POST看你后端需求),不用提前设action
<form name="form1" method="GET">
  <input type="hidden" name="id" id="id" value="<?php echo $row['id'];?>">
  <select name="select" onchange="goto(this.form)">
    <option value="">-------Choose a Selection-------</option>
    <option value="view.php">View</option>
    <option value="download.php">Download</option>
  </select>
</form>
  1. 重写你的goto函数,先把选中的页面设为表单的action,再提交表单:
function goto(form) {
  const selectedIndex = form.select.selectedIndex;
  const selectedValue = form.select.options[selectedIndex].value;
  
  // 跳过默认的空选项,啥也不做
  if (!selectedValue.trim()) return;
  
  // 把选中的页面设为表单要提交到的地址
  form.action = selectedValue;
  // 提交表单!这一步会把包括隐藏id在内的所有表单字段都发过去
  form.submit();
}
  • 要是用method="GET",后端用$_GET['id']就能拿到值,地址栏会显示view.php?id=xxx
  • method="POST"的话,后端用$_POST['id']获取,地址栏不会暴露id,更安全点。

方法二:直接把id拼到URL后面跳转(只适合GET请求)

如果你不想改表单提交的方式,也可以直接在跳转的时候把id拼到目标URL后面,修改goto函数就行:

function goto(form) {
  const selectedIndex = form.select.selectedIndex;
  const selectedValue = form.select.options[selectedIndex].value;
  
  if (!selectedValue.trim()) return;
  
  // 把id拼到URL后面,记得用encodeURIComponent转义特殊字符
  const targetUrl = `${selectedValue}?id=${encodeURIComponent(form.id.value)}`;
  location.href = targetUrl;
}

这种方式直接跳转,不用提交表单,但只能用GET传参,而且如果id里有空格、&这类特殊字符,一定要用encodeURIComponent转义,不然会出问题。

对了,顺便提一句,你原来的代码里有些<option>没加闭合的</option>,最好补上,不然浏览器可能会解析出奇怪的问题哦。

备注:内容来源于stack exchange,提问作者FireNet

火山引擎 最新活动