如何让<select>的name不显示在URL中?表单URL结构优化
你现在遇到的问题是表单默认的GET提交机制会把<select>的name作为参数名、选项值作为参数值拼到URL里,但你需要把选中的酒店标识(带locale参数)直接追加到/properties/路径后面对吧?这个问题很好解决,核心思路是动态修改表单的action属性,而不是依赖默认的参数拼接逻辑。
这里有个简单的前端实现方案,不需要后端支持:
1. 调整表单基础结构
首先给表单添加id方便JavaScript操作,同时移除<select>的name属性(因为我们不需要它作为查询参数传递):
<form id="propertyQueryForm" action="https://website.com/properties/" method="GET"> Sucursal:<br> <select id="hotelSelector" required> <option value="hotelvinadelmar?locale=es">Viña del Mar</option> <option value="hotelsantiago1?locale=es">Nueva Providencia</option> <option value="hotelsantiago2?locale=es">Providencia</option> </select> <br><br> <!-- 以下是你的其他表单字段 --> <input type="text" name="check_in_date" placeholder="Check In (DD-MM-YYYY)" required> <input type="text" name="check_out_date" placeholder="Check Out (DD-MM-YYYY)" required> <input type="number" name="number_adults" min="1" required> <input type="number" name="number_children" min="0" required> <br><br> <button type="submit">提交查询</button> </form>
2. 添加JavaScript动态更新表单action
通过监听<select>的选择变化,实时修改表单的action属性,把选中的酒店标识追加到基础路径后:
const hotelSelector = document.getElementById('hotelSelector'); const queryForm = document.getElementById('propertyQueryForm'); // 页面加载时,先设置默认选中项对应的action queryForm.action += hotelSelector.value; // 监听选择切换事件,更新action hotelSelector.addEventListener('change', function() { // 重置为基础路径,再拼接当前选中的酒店标识 queryForm.action = `https://website.com/properties/${this.value}`; });
为什么这个方案能满足需求?
当表单以GET方式提交时,浏览器会自动把所有带有name属性的表单控件(比如日期、成人/儿童数量)转换成查询参数,附加在表单action的末尾。我们通过动态修改action,已经把酒店代码和locale参数整合到了URL路径中,最终提交后的URL就会完全符合你想要的格式:
https://website.com/properties/hotelvinadelmar?locale=es&check_in_date=22-03-2019&check_out_date=25-03-2019&number_adults=4&number_children=9
备选方案(如果不想用JS)
如果你的项目限制使用JavaScript,可以考虑在后端做重定向:让表单提交到一个中间接口,后端接收原test参数的值后,重定向到目标URL。不过这种方式需要后端开发支持,不如前端动态修改action来得直接高效。
内容的提问来源于stack exchange,提问作者Jun Junnagrio

