使用JavaScript实现表单提交后页面跳转失败问题求助
问题解决:表单提交后无法正常跳转页面
问题原因分析
- 表单默认提交行为干扰:你的按钮是
type="submit",点击时会优先触发表单的默认提交逻辑,将数据发送到action="/create"地址,导致JavaScript跳转代码被覆盖,这就是出现空白页的核心原因(后端可能未返回有效内容)。 - 跳转语法错误:
window.location是对象而非函数,直接调用window.location("url")属于语法错误,正确写法应为window.location.href = "url"或window.location.assign("url")。
解决方案
方案一:阻止默认提交 + 修正跳转代码
修改JavaScript函数,加入阻止默认行为的逻辑,同时修正跳转写法:
function loadPage(event){ // 阻止表单默认提交行为 event.preventDefault(); // 正确执行页面跳转 window.location.href = "http://localhost:8080/list"; }
同时修改按钮的onclick事件,传递事件对象:
<button onclick="loadPage(event)" id="button" type="submit" class="btn btn btn-danger">ENVIAR</button>
方案二:修改按钮类型避免默认提交
如果不需要表单的默认提交逻辑(比如已通过其他方式处理数据),直接将按钮type改为button:
<button onclick="loadPage()" id="button" type="button" class="btn btn btn-danger">ENVIAR</button>
同步修正跳转函数:
function loadPage(){ window.location.href = "http://localhost:8080/list"; }
方案三:事件监听绑定(推荐现代写法)
移除内联onclick,用JavaScript绑定表单提交事件,代码更清晰易维护:
<form class="form-group" action="/create" method="post" enctype="multipart/form-data" id="productForm"> <!-- 表单原有内容不变 --> <button id="button" type="submit" class="btn btn btn-danger">ENVIAR</button> </form> <script type="text/javascript"> document.getElementById('productForm').addEventListener('submit', function(event) { event.preventDefault(); // 阻止默认提交 window.location.href = "http://localhost:8080/list"; // 执行跳转 }); </script>
补充说明
如果你的需求是先提交表单数据到后端,再跳转页面,上述方法会阻止表单提交,此时应该让后端在处理完数据后,返回重定向响应(比如302状态码指向/list),这是表单提交场景下的标准流程。
内容的提问来源于stack exchange,提问作者Guilherme Rodrigues
相关产品推荐
相关产品推荐

