[译] JavaScript (XMLHttpRequest) 读取二进制数据流
Posted by bianbian on 2008-04-06 13:36
本文Tags: AJAX, Firefox, JavaScript, XMLHttpRequest, 二进制, 数据
译者注:原来想用JS直接处理C丢过来的struct数据,具体可以查看:[原] C的struct和JSON交互。
经过千辛万苦的查找,找到了这篇文章(作者应该比我更辛苦):Downloading Binary Streams with Javascript XMLHttpRequest
把关键点翻译如下(不过我还没有测试):
利用XMLHttpRequest的overrideMimeType方法设置charset为x-user-defined。
- //fetches BINARY FILES synchronously using XMLHttpRequest
- load_url = function(url) {
- netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
- var req = new XMLHttpRequest();
- req.open('GET',url,false);
- //XHR binary charset opt by Marcus Granado 2006 [http://mgran.blogspot.com]
- req.overrideMimeType('text/plain; charset=x-user-defined');
- req.send(null);
- if (req.status != 200) return '';
- return req.responseText;
- }
- var filestream = load_url(url);
- var abyte = filestream.charCodeAt(x) & 0xff;
IE不支持overrideMimeType方法,不过有评论者说VBScript可以实现:
- Dim xhr
- Set xhr = CreateObject("Microsoft.XMLHTTP")
- xhr.Open "GET", "folder.bin", False
- xhr.setRequestHeader "Accept-Charset", "x-user-defined"
- xhr.setRequestHeader "Content-Type", "application/pdf"
- xhr.send Null
遵守创作共用协议,转载请链接形式注明来自http://bianbian.org 做人要厚道