代碼中使用全局變量 xmlHttp,發起多個並發請求時,後發請求覆蓋前請求的 xmlHttp 引用,導致回調函數讀取到錯誤的響應對象,最終只顯示最後一個請求結果。
function loadSelectData(selectId, url, paramName, paramValue) {
const xhr = new XMLHttpRequest(); // 局部變量,每調用一次創建一個
xhr.open('GET', url + '?' + paramName + '=' + encodeURIComponent(paramValue), true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
document.getElementById(selectId).innerHTML = xhr.responseText;
}
};
xhr.send();
}
// 使用示例:演出選擇後聯動時間、地點、票價
document.getElementById('showSelect').onchange = function() {
const showId = this.value;
loadSelectData('timeSelect', '/api/times', 'showId', showId);
loadSelectData('placeSelect', '/api/places', 'showId', showId);
loadSelectData('priceSelect', '/api/prices', 'showId', showId);
};
function fetchHTML(url, params) {
const query = new URLSearchParams(params).toString();
return fetch(url + '?' + query).then(r => r.ok ? r.text() : Promise.reject(r.status));
}
async function updateAll(showId) {
try {
const [times, places, prices] = await Promise.all([
fetchHTML('/api/times', {showId}),
fetchHTML('/api/places', {showId}),
fetchHTML('/api/prices', {showId})
]);
document.getElementById('timeSelect').innerHTML = times;
document.getElementById('placeSelect').innerHTML = places;
document.getElementById('priceSelect').innerHTML = prices;
} catch (err) { console.error('聯動失敗', err); }
}
XMLHttpRequest 實例。fetch Promise 綁定請求上下文。