var usersname; // 全域變數
$.ajax({
url: 'a.action',
type: 'POST',
success: function(data) {
usersname = data; // 看似賦值成功
}
});
console.log(usersname); // undefined!因為 AJAX 尚未完成
**AJAX 預設非同步** (`async: true`)。`$.ajax` 發送請求後**立即返回**,主執行緒繼續執行 `console.log`,此時回調函式尚未被事件佇列執行,全域變數仍為初始值。
$.ajax({
async: false, // 阻塞瀏覽器主執行緒,直到請求完成
success: function(data) { usersname = data; }
});
console.log(usersname); // 此時已有值
嚴重缺點:
function fetchUserName(callback) {
$.ajax({
url: 'a.action',
success: function(data) {
callback(data); // 將資料傳給後續邏輯
}
});
}
// 使用
fetchUserName(function(name) {
usersname = name;
renderUI(); // 所有依賴 usersname 的操作放在這裡
});
function fetchUserName() {
return $.ajax({ url: 'a.action' }); // 回傳 Promise-like (jqXHR)
}
// ES2017 async/await
async function init() {
try {
const name = await fetchUserName();
usersname = name;
renderUI();
} catch (err) {
console.error('取得失敗', err);
}
}
init();
// 簡易 EventBus
const EventBus = {
_events: {},
on(event, fn) { (this._events[event] = this._events[event] || []).push(fn); },
emit(event, data) { (this._events[event] || []).forEach(fn => fn(data)); }
};
// 資料層
$.ajax({ url: 'a.action' }).done(data => EventBus.emit('user:nameLoaded', data));
// UI 層 (任意處註冊)
EventBus.on('user:nameLoaded', name => {
usersname = name;
renderUI();
});
// utils/api.js
export function request(url, options = {}) {
return $.ajax({
url,
type: options.method || 'GET',
data: options.params,
dataType: 'json',
headers: options.headers,
timeout: 10000
}).then(
res => res, // 成功直接解析 data
(jqXHR, textStatus) => {
const err = new Error(textStatus);
err.status = jqXHR.status;
err.response = jqXHR.responseJSON;
throw err; // 統一拋出,供上層 catch
}
);
}
// 使用
import { request } from './utils/api';
async function loadUser() {
try {
const name = await request('/a.action');
usersname = name;
renderUI();
} catch (e) {
showToast(e.message);
}
}
| 方案 | 優點 | 缺點 | 推薦度 |
|---|---|---|---|
| async:false | 代碼最少、同步寫法直觀 | 阻塞主執行緒、棄用標準、體驗極差 | ❌ 禁止 |
| Callback | 相容舊環境、無依賴 | 回調地獄、錯誤處理分散 | ⚠️ 維護舊碼 |
| Promise/async-await | 線性閱讀、統一錯誤處理、易除錯 | 需 ES2017+ 或 Polyfill | ✅ 首選 |
| EventBus | 解耦、多訂閱者、跨組件通訊 | 間接性強、除錯需追蹤事件流 | ✅ 大型應用 |