ajax 传递arraybuffer,jQuery $ .ajax或$ .load是否允许responseType arrayBuffer?

小编典典

关于您的问题,jQuery似乎还不支持它。在按照我下面的建议使用它之前,请考虑检查该功能是否可用。

使用XHTMLRequest,您可以欺骗您的服务器,并从服务器接收一个代表您想要的字节的二进制字符串。它完美地工作。

var xhr = new XMLHttpRequest();

xhr.open('GET', '/your/audio/file.wav', true);

// Here is the hack

xhr.overrideMimeType('text/plain; charset=x-user-defined');

xhr.onreadystatechange = function(event) {

if ( this.readyState == 4 && this.status == 200 ) {

var binaryString = this.responseText;

for (var i = 0, len = binaryString.length; i < len; ++i) {

var c = binaryString.charCodeAt(i);

var byte = c & 0xff; //it gives you the byte at i

//Do your cool stuff...

}

}

};

xhr.send();

它可以正常工作,但是…仍然是一个hack。

使用XHTML Request Level

2,您可以将responseType指定为’arraybuffer’并实际接收ArrayBuffer。好多了。问题是检查您的浏览器是否支持此功能。

var xhr = new XMLHttpRequest();

xhr.open('GET', '/your/audio/file.wav', true);

xhr.responseType = 'arraybuffer';

xhr.onload = function(e) {

if (this.status == 200) {

//Do your stuff here

}

};

xhr.send();

希望我能帮上忙。

2020-07-26