// 點擊鏈接發 AJAX,拿到 responseText 彈 alert
alert(request.responseText); // 體驗極差,且無法交互
AJAX = 異步獲取數據 + 局部更新,不刷新頁面、不跳轉。若要跳轉,直接用 ``;若要彈窗展示內容,需:
responseText)。div + CSS 定位)。innerHTML 或 $(modal).html(data)。<style>
.modal { display:none; position:fixed; top:50%; left:50%; transform:translate(-50%,-50%); background:#fff; padding:20px; border:1px solid #ccc; z-index:999; max-width:80%; max-height:80%; overflow:auto; }
.mask { display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.5); z-index:998; }
</style>
<div id="mask" class="mask"></div>
<div id="modal" class="modal"></div>
<script>
document.querySelectorAll('a.ajax-modal').forEach(a => {
a.onclick = e => {
e.preventDefault();
fetch(a.href).then(r => r.text()).then(html => {
document.getElementById('modal').innerHTML = html;
document.getElementById('mask').style.display = 'block';
document.getElementById('modal').style.display = 'block';
});
};
});
document.getElementById('mask').onclick = () => {
document.getElementById('mask').style.display = 'none';
document.getElementById('modal').style.display = 'none';
};
</script>
Bootstrap Modal、Layer、SweetAlert2,處理居中、拖拽、Esc 關閉、無障礙等細節。**AJAX 的價值在於「不離開當前頁完成交互」**,彈窗只是展示形式之一。