萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

AJAX 成功回調中實現頁面跳轉的最佳實踐

場景

在前端開發中,常見需求:發送 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('網路錯誤,請稍後再試');
  }
});

關鍵點解析

  • 同步 vs 非同步:AJAX 預設非同步,success 回調在伺服器回應後執行,此時操作 window.location 完全安全。
  • 回傳格式:建議伺服器回傳 JSON,包含 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,請求完成再啟用

原生 fetch 寫法(現代專案推薦)

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('網路錯誤');
  }
}
copyright © 萬盛學電腦網 all rights reserved