2015-04-03 84 views
0

我正在研究使用closure frameworkhttps://github.com/google/shaka-player)的JavaScript应用程序。关闭js框架 - 将ArrayBuffer转换为字符串

我收到一个带有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的构造函数。有没有办法让响应保持安静?

回答

1

如果responseTyp的是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]); 
    } 

} 

希望这会帮助你。

+0

感谢,但我的问题是,变种AB =新Uint8Array(this.xhr_.response);失败了。 – 2015-04-03 12:29:11

1

我发现一个可行的解决方案 - 如何在封闭的框架投 - 我希望这可以帮助别人

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); 
} 
+1

不依赖于Closure框架。如果您需要将ArrayBuffer转换为字符串,这对于香草很适用。 – Touffy 2015-04-03 12:52:06

+0

我猜 - 但依赖部分是/ ** @type {ArrayBuffer} * /实际上在闭包框架中具有强制转换的效果 - 如果没有这个,构建将会失败。 – 2015-04-03 13:26:01