如何实现HTML/JS表单提交至URL1后重定向至URL2?
实现表单提交后跳转指定页面的方案
因为无法控制目标提交地址https://1111.example.com的重定向逻辑,我们可以通过以下两种方式实现需求:
方案1:用JavaScript拦截提交事件,发送请求后手动重定向
核心逻辑:阻止浏览器默认的表单提交跳转,通过Fetch API发送数据,请求完成后主动跳转到目标页面。
修改后代码
<form action="https://1111.example.com" method="get" id="myForm"> <p><label for="a">a</label><input type="text" name="a" id="a" /></p> <p><label for="b">b</label><input type="text" name="b" id="b" /></p> <p><input type="submit" id="submit" class="button" value="Submit" /></p> </form> <script> document.getElementById('myForm').addEventListener('submit', async function(e) { // 阻止默认提交跳转 e.preventDefault(); // 收集表单数据并转为GET请求参数 const formData = new FormData(this); const paramStr = new URLSearchParams(formData).toString(); const requestUrl = `${this.action}?${paramStr}`; try { // 发送GET请求 await fetch(requestUrl, { method: 'GET' }); // 请求完成后跳转到指定页面 window.location.href = 'https://2222.example.com'; } catch (err) { // 可根据需求处理请求失败场景,比如提示用户后再跳转 console.error('提交失败:', err); window.location.href = 'https://2222.example.com'; } }); </script>
方案2:通过隐藏iframe提交表单,完成后重定向
核心逻辑:让表单在隐藏的iframe中提交,避免当前页面跳转,监听iframe加载完成事件后执行重定向(兼容性更好,适合老浏览器场景)。
修改后代码
<!-- 添加隐藏iframe --> <iframe id="hidden-submit-frame" name="hidden-submit-frame" style="display: none;"></iframe> <form action="https://1111.example.com" method="get" target="hidden-submit-frame"> <p><label for="a">a</label><input type="text" name="a" id="a" /></p> <p><label for="b">b</label><input type="text" name="b" id="b" /></p> <p><input type="submit" id="submit" class="button" value="Submit" /></p> </form> <script> document.getElementById('hidden-submit-frame').addEventListener('load', function() { // iframe加载完成(即表单提交完成)后跳转 window.location.href = 'https://2222.example.com'; }); </script>
注意:如果https://1111.example.com设置了X-Frame-Options禁止嵌入,方案2会失效,此时优先使用方案1。
内容的提问来源于stack exchange,提问作者james1052
相关产品推荐
相关产品推荐

