表單提交觸發 JS 函數:
function mySubmitFn() {
formname.submit(); // 程式碼1:提交表單,後端返回 redirect:A.jsp
window.location.href = 'B.jsp'; // 程式碼2:前端強制跳轉 B.jsp
}
實測先執行程式碼2 跳轉 B.jsp,後端 redirect A.jsp 失效。
form.submit() 是**非同步**發送請求,瀏覽器**不會等待**回應就繼續執行下一行 JS。window.location.href 導航離開,重導向會被忽略或在新頁面中無效。function mySubmitFn() {
fetch('/submit', { method: 'POST', body: new FormData(formname) })
.then(r => r.json())
.then(data => {
if (data.success) window.location.href = data.redirectUrl; // 由後端決定
});
}
<form action="/submit" method="post"> ... </form>
// 後端 Controller
@PostMapping("/submit")
public String submit(...) {
return "redirect:/A.jsp"; // 或 redirect:/success
}
$.post("/submit", $(form).serialize(), function(resp) {
if (resp.url) window.location.href = resp.url;
});
window.location.href,完全交給後端 RedirectView。