如何将PHP页面的querystring值传递到HTML页面并存为隐藏表单字段?
解决方案
问题原因
- 原有代码仅读取了URL参数,没有执行赋值操作将参数写入隐藏输入框
- 自定义正则匹配的参数读取方法容易出现字符转义类的兼容性问题,可替换为更稳定的原生API
最优实现方案(兼容所有现代浏览器)
使用原生URLSearchParamsAPI读取query参数,逻辑更稳定不易出错:
<!-- 原有隐藏字段 --> <input type="hidden" name="recid" /> <!-- 记得提前引入jQuery --> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script type="text/javascript"> $(document).ready(function () { // 读取URL参数 const urlParams = new URLSearchParams(window.location.search); const recId = urlParams.get('recid'); // 赋值给隐藏字段,也可写为$('input[name="recid"]').val(recId) $('input[name="recid"]').val(recId); // 调试用,不需要可删除 console.log('获取到的recid值:', recId); }); </script>
兼容IE等旧浏览器的实现方案
如果需要兼容老旧浏览器,调整原有代码的逻辑顺序、增加赋值操作即可:
<input type="hidden" name="recid" /> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script type="text/javascript"> // 把函数定义提到作用域最前,避免提升异常 function getParameterByName(id) { id = id.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new RegExp("[\\?&]" + id + "=([^&#]*)"), results = regex.exec(location.search); return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); } $(document).ready(function () { var x = getParameterByName("recid"); alert("recid : " + x); // 新增赋值到隐藏字段的逻辑 $('input[name="recid"]').val(x); }); </script>
异常排查
如果仍然获取不到参数值,按以下步骤检查:
- 打开edit.html页面后,先确认浏览器地址栏的URL中确实存在
?recid=xxx参数,参数名的大小写、拼写完全匹配 - 检查PHP生成的跳转链接格式是否正确,正确生成的链接格式应为
edit.html?recid=实际ID值,不要在ID值前后额外拼接单引号等多余符号
内容的提问来源于stack exchange,提问作者Kenny
相关产品推荐
相关产品推荐

