使用Ajax请求API获取PDF时出现XMLHttpRequest.responseText错误
Ajax请求PDF文件抛出DOMException错误的解决办法
错误信息
未捕获DOMException:XMLHttpRequest.responseText 获取器:仅当responseType为''或'text'时,responseText才可用。
原代码
$.ajax({ cache: false, contentType: "application/json", type: "GET", url: url, processData: false, xhrFields: { responseType: "blob" }, success: function (response, status, xhr) { console.log("succuess") console.log(response) console.log(status) console.log(xhr) try { //ShowModalCargando(false); let blob = new Blob([response], { type: 'application/pdf' }); let URL = window.URL || window.webkitURL; let downloadUrl = URL.createObjectURL(blob); if (elemento === null) window.open(downloadUrl); else { let iFrame = document.getElementById(elemento); iFrame.src = downloadUrl; } } catch (ex) { ShowModalCargando(false); console.log(ex); } }, error: function (err) { ShowModalCargando(false); console.log("Error al intentar realizar la impresion: " + JSON.stringify(err)); } });
已尝试的无效方案
- 移除content-type配置,无效
- 移除xhr的responseType配置,返回空白PDF
- 升级jQuery版本(当前使用jQuery 1.11.3),无效
- 在Chrome和火狐浏览器测试均失败
- Postman请求该API可正常获取PDF内容
解决办法
问题出在jQuery 1.11.3的$.ajax内部逻辑:当设置responseType: 'blob'时,jQuery仍会尝试访问responseText属性,而该属性仅在responseType为文本类时可用,因此抛出错误。直接使用原生XMLHttpRequest即可绕过这个问题:
var xhr = new XMLHttpRequest(); xhr.open('GET', url, true); // 指定返回类型为blob xhr.responseType = 'blob'; xhr.onload = function() { if (xhr.status === 200) { console.log("success"); try { // 直接使用xhr.response,已为blob类型,无需重新包装 let blob = xhr.response; let URL = window.URL || window.webkitURL; let downloadUrl = URL.createObjectURL(blob); if (elemento === null) { window.open(downloadUrl); } else { let iFrame = document.getElementById(elemento); iFrame.src = downloadUrl; } } catch (ex) { ShowModalCargando(false); console.log(ex); } } else { ShowModalCargando(false); console.log("打印请求失败:" + xhr.statusText); } }; xhr.onerror = function() { ShowModalCargando(false); console.log("请求发送出错"); }; // 发送请求,GET请求无需传参 xhr.send();
额外检查项
确保后端API返回的响应头中Content-Type值为application/pdf,这是浏览器正确识别PDF内容的前提。
内容的提问来源于stack exchange,提问作者David081
相关产品推荐
相关产品推荐

