我已经使用同步XMLHttpRequest并将responseType设置为"arraybuffer“很长一段时间了,以便加载二进制文件并等待加载完成。今天,我收到了这个错误:"Die Verwendung des responseType-Attributes von XMLHttpRequest wird im synchronen Modus im window-Kontekt nicht mehr unterstützt“。这大致翻译为“在window-context(?)不再支持同步模式下XMLHttpRequest的responseType的用法”。
有人知道怎么解决这个问题吗?我真的不想对这样的事情使用异步请求。
var xhr = new XMLHttpRequest();
xhr.open('GET', url, false);
xhr.responseType = 'arraybuffer';
在chrome中工作正常。
发布于 2020-09-16 20:57:02
由于不可能将responseType = 'arraybuffer'
设置为同步模式,因此接收字符串并转换为字节是一种解决方案,但正如斯蒂芬所说,您的数据应该是ascii文本。您将收到错误的值(253),而不是127以上的所有字节。
但是将mime-type
和charset设置为x-user-defined
可能是一种解决方案:
这里服务器发送从125到134的10个字节:
request = new XMLHttpRequest();
request.overrideMimeType('text/plain; charset=x-user-defined');
request.open('GET', url, false);
request.send();
Uint8Array.from(request.response, c => c.charCodeAt(0));
> Uint8Array(10) [125, 126, 127, 128, 129, 130, 131, 132, 133, 134]
如果不设置mime-type,则如下所示:
request = new XMLHttpRequest();
request.open('GET', url, false);
request.send();
Uint8Array.from(request.response, c => c.charCodeAt(0));
> Uint8Array(10) [125, 126, 127, 253, 253, 253, 253, 253, 253, 253]
发布于 2018-12-31 01:36:32
如果您足够幸运地控制了整个页面的入口点,那么可以考虑用一个async
函数包装整个页面,并使用await
阻塞有问题的异步代码。然而,可能并不是所有的用例都适用。
(async function () {
await problem_function_1();
await problem_function_2();
... normal page logic pasted here ...
})();
使用Promise
包装不是promise的异步代码(以便await按预期工作),并在任何构成“成功回调”的地方手动调用resolve函数。如果可能,对reject执行相同的操作。
https://stackoverflow.com/questions/9855127
复制相似问题