突然禁止设置XMLHttpRequest.responseType?

Mar*_*kus 19 javascript ajax firefox xmlhttprequest

我一直在使用同步XMLHttpRequest,其responseType设置为"arraybuffer"很长一段时间来加载二进制文件并等到它被加载.今天,我收到了这个错误:"Die Verwendung des responseType-Attributes von XMLHttpRequest wird im synchronen Modus im window-Kontekt nichtmehrunterstützt." 大致转换为"不再支持在窗口上下文(?)中以同步模式使用XMLHttpRequest的responseType."

有谁知道如何解决这一问题?我真的不想对这样的事情使用异步请求.

var xhr = new XMLHttpRequest();
xhr.open('GET', url, false);
xhr.responseType = 'arraybuffer';
Run Code Online (Sandbox Code Playgroud)

镀铬工作正常.

Rob*_*b W 13

这是正确的行为,如XMLHttpRequest规范中所定义:

设置时:如果设置"InvalidAccessError"同步 标志并且存在关联的XMLHttpRequest文档,则抛出异常.

responseTypeXMLHttpRequest不是异步时,也就是同步时,不能设置该属性.设置opento 的第三个参数false会导致请求同步.

  • @Markus重点是你不应该编写使用同步XHR的新代码.完全删除它会破坏现有网站,但浏览器和规范试图限制其在新代码中的使用,以便新代码实际上做正确的事情并使用异步XHR. (3认同)

Ste*_*han 9

解决方法

对于休闲阅读器,如果仍需要同步行为,则可以将内容下载为字符串,然后将其转换为字节数据

NOTA:
此解决方法假定原始文本request.responseASCII文本.
如果此假设不适合您的特定用例,请参阅jBinary.

我将它转换为ArrayBuffer.

var request = new XMLHttpRequest();
request.open('GET', url, false);
request.send(null);

var data;
if (request.status === 200) {
    data = stringToArrayBuffer(request.response);
} else {
    alert('Something bad happen!\n(' + request.status + ') ' + request.statusText);
}

// ...

function stringToArrayBuffer(str) {
    var buf = new ArrayBuffer(str.length);
    var bufView = new Uint8Array(buf);

    for (var i=0, strLen=str.length; i<strLen; i++) {
        bufView[i] = str.charCodeAt(i);
    }

    return buf;
}
Run Code Online (Sandbox Code Playgroud)

更多阅读

参考

  • 我怀疑二进制文本二进制转换没有产生原始字节 (3认同)

ima*_*man 9

由于无法设置responseType = \'arraybuffer\'同步模式,因此接收字符串并转换为字节是一种解决方案,但正如 Stephan 所说,您的数据应该是 ascii 文本。您将收到错误的值 (253),而不是高于 127 的所有字节。

\n

但设置mime-type和字符集x-user-defined可能是一个解决方案:

\n

这里服务器发送从 125 到 134 的 10 个字节:

\n
request = new XMLHttpRequest();\nrequest.overrideMimeType(\'text/plain; charset=x-user-defined\');\nrequest.open(\'GET\', url, false);\nrequest.send();\nUint8Array.from(request.response, c => c.charCodeAt(0));\n> Uint8Array(10)\xc2\xa0[125, 126, 127, 128, 129, 130, 131, 132, 133, 134]\n
Run Code Online (Sandbox Code Playgroud)\n

不设置 mime-type 是这样的:

\n
request = new XMLHttpRequest();\nrequest.open(\'GET\', url, false);\nrequest.send();\nUint8Array.from(request.response, c => c.charCodeAt(0));\n> Uint8Array(10)\xc2\xa0[125, 126, 127, 253, 253, 253, 253, 253, 253, 253]\n
Run Code Online (Sandbox Code Playgroud)\n