闭包js框架 - 将ArrayBuffer转换为字符串

时间:2015-04-03 11:16:19

标签: javascript ajax google-closure

我正在处理使用closure frameworkhttps://github.com/google/shaka-player)的JavaScript应用。

我收到带有403响应的ajax响应,我需要解析响应主体以确定详细信息。

xhr_.responseType设置为arraybuffer - 所以我希望能够将响应转换为字符串以读取其内容:

if (this.xhr_.responseType == 'arraybuffer')
{
    var ab = new Uint8Array(this.xhr_.response);
    console.log(this.xhr_.response);
    console.log(ab);
}

使用闭包框架构建,我收到以下错误:

./build/../build/../lib/util/ajax_request.js:441: ERROR - actual parameter 1 of Uint8Array does not match formal parameter
found   : *
required: (Array.<number>|ArrayBuffer|ArrayBufferView|null|number)
      var ab = new Uint8Array(this.xhr_.response);

所以我发现无法将响应传递给Uint8Array构造函数。有没有办法施放响应以保持关闭安静?

2 个答案:

答案 0 :(得分:1)

如果responsetype是arraybuffer,那么你需要以这种方式循环:

if (this.xhr_.responseType == 'arraybuffer')
{
    var ab = new Uint8Array(this.xhr_.response);
    for (var i = 0, buffer = ''; i < ab.length; i++) 
    {
        buffer += String.fromCharCode(payload[i]);
    }

}

希望这会对你有所帮助。

答案 1 :(得分:1)

我找到了一个有效的解决方案 - 如何在Closure框架中进行投射 - 我希望这有助于某人

if (this.xhr_.responseType == 'arraybuffer')
{
    var response = /** @type {ArrayBuffer} */ (this.xhr_.response);
    var sBuffer = String.fromCharCode.apply(null, new Uint8Array(response));
    console.log('response ArrayBuffer to string: ' + sBuffer);
}