首页 > 开发 > 前端 > 正文

ajax 中获取和发送二进制数据的方法

2016-04-17 22:34:48  来源:慕课网

项目中用到二进制数据 ,一般的ajax请求并不能满足需求,所以看了下XMLHttpRequest对象,用xhr.response来获得二进制数据,而不是responseText,示例如下:
var xhr = new XMLHttpRequest();
xhr.open('GET',url, true);
xhr.responseType = 'blob'; // 二进制大对象
xhr.onload = function(e) {
if (this.status == 200) {
// get binary data as a response
var blob = this.response;
}
};
xhr.send();

// 真正方法
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
// response is unsigned 8 bit integer
var responseArray = new Uint8Array(this.response);
// 下面对二进制数据的处理
};
xhr.send();