問題現象:使用 $.ajax 請求後端導出 Excel(返回 Content-Disposition: attachment),瀏覽器不彈出「保存/打開」下載對話框。
$.ajax 屬於 XHR 請求,瀏覽器將響應體交給 JavaScript 處理,不觸發原生文件下載機制。即使設置 dataType: 'json' 或處理 blob,亦需手動創建 <a> 標籤觸發下載,體驗較差。
window.showModalDialog(url):僅彈出空白窗口,不觸發下載(IE 專有,現代瀏覽器已棄用)。window.open
window.open(ActionUrl + '?action=export&ID=' + $('#fm_ID').val());
原理:window.open 發起標準導航請求,瀏覽器識別響應頭 Content-Disposition: attachment,自動彈出下載框,體驗與直接輸入 URL 一致。
Content-Type: application/vnd.ms-excel、Content-Disposition: attachment; filename="xxx.xls"。POST 表單提交(動態創建 <form target="_blank">)。Response.OutputStream 即可,無需返回 JSON。AJAX 無法直接觸發文件下載,window.open 是最簡單、兼容性最好的繞過方案。若需 POST 或大參數,用隱藏表單 target="_blank" 提交。前端下載文件,導航請求才是正道。