在前端開發中,常見需求:發送 AJAX 請求,伺服器驗證成功後,需將瀏覽器導向新頁面(如登入成功跳轉首頁、表單提交後導向列表頁)。
$.ajax({
url: '/login',
type: 'POST',
data: { username: 'admin', password: '123456' },
success: function(response) {
if (response.success) {
// 方式一:直接跳轉(當前頁面替換)
window.location.href = response.redirectUrl || '/dashboard';
// 方式二:新分頁開啟(視需求而定)
// window.open(response.redirectUrl, '_blank');
} else {
alert('登入失敗:' + response.message);
}
},
error: function(xhr) {
console.error('請求異常', xhr);
alert('網路錯誤,請稍後再試');
}
});
success 回調在伺服器回應後執行,此時操作 window.location 完全安全。success、message、redirectUrl 等欄位,前端統一處理。success 中使用 alert() 後再跳轉,會延遲導向體驗;若需提示,可用非阻塞 Toast 通知。| 問題 | 原因 | 解決方案 |
|---|---|---|
| 跳轉不生效 | 伺服器回傳 302 重導向,瀏覽器自動跟隨,導致 AJAX 回調拿到的是重導向後的頁面 HTML | 伺服器針對 AJAX 請求回傳 JSON 而非 302;或前端設 xhrFields: {withCredentials: true} 配合後端處理 |
| 跳轉後頁面空白 | window.location.href 賦值為空字串或錯誤 URL | 嚴格檢查 redirectUrl 非空,必要時 console.log 除錯 |
| 表單重複提交 | 使用者連點按鈕觸發多次 AJAX | 按鈕點擊後立即 disabled = true,請求完成再啟用 |
async function login() {
try {
const res = await fetch('/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: 'admin', password: '123456' })
});
const data = await res.json();
if (data.success) window.location.href = data.redirectUrl;
else alert(data.message);
} catch (e) {
console.error(e);
alert('網路錯誤');
}
}