使用: 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能夠自動按照設置的值進行解析.