使用: xhr.responseType; 这个属性可读写, 也就是说, 我们可以在xhr.open()之后, 在xhr.send()之前, 设置 xhr.responseType属性, 使其告诉服务器客户端需要什么类型的数据;

xhr.responseType 的属性值可以是: 

1. 空字符串: "", 等同于text, 表示服务器返回文本数据;

2. ArrayBuffer对象: "arraybuffer" , 表示服务器返回二进制数组;

3. Blob对象: "blob", 表示服务器返回二进制对象;

4. JSON对象: "json";

5. 字符串: "text"

下面是一个xhr.responseType 为 blob 的示例:

var xhr = new XMLHttpRequest(); 
xhr.open('GET', '/path/to/image.png', true); 
xhr.responseType = 'blob'; 
 
xhr.onload = function(e) { 
  if (this.status === 200) { 
    var blob = new Blob([xhr.response], {type: 'image/png'}); 
    // 或者 
    var blob = xhr.response; 
  } 
}; 
 
xhr.send();

 

注意: 不是说xhr.responseType设置什么类型, 服务器就返回什么类型, 这个是需要前后端沟通的, 对xhr.responseType属性的设置其实主要是为了xhr.response能够自动按照设置的值进行解析. 

评论关闭
IT源码网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!

怎样获取从服务器返回的数据体