前端跟后端通过ajax请求来传输数据,服务端通常会返回json数据来处理,我们可以通过设置 XMLHttpRequest.responseType 返回服务器响应的数据类型,如果不设置或者设置为 "" 会使用 text 类型返回

responseType 必须设置跟服务器返回的类型是兼容的,否则就算浏览器返回了数据,前端也可能收到 null

responseType可选值

描述
"" 跟设置 text 相同,实际上是 DOMString
text response 是包含在 DOMString 对象中的文本
arraybuffer response 是一个包含二进制数据的 JavaScript ArrayBuffer 
blob response 是一个包含二进制数据的 Blob 对象
document response 是一个 HTML Document 或 XML XMLDocument ,这取决于接收到的数据的 MIME 类型
json response 是一个 JavaScript 对象。这个对象是通过将接收到的数据类型视为 JSON 解析得到的,这个也是使用最多的情况

arrayBuffer的应用(服务器二进制流转图片)

var oReq = new XMLHttpRequest();
oReq.open("GET", "/myfile.png", true);
oReq.responseType = "arraybuffer";

oReq.onload = function(oEvent) {
  const blob = new Blob([oReq.response], {type: "image/png"});
  const url = window.URL.createObjectURL(blob)
  console.log(url)
};
oReq.send();

blob的应用(服务器二进制流转图片)

// 使用 responseType = 'blob' 来实现
oReq.responseType = "blob";

oReq.onload = function(oEvent) {
  const blob = oReq.response;
  const url = window.URL.createObjectURL(blob)
  console.log(url)
}

在老的浏览器接受二进制数据

function load_binary_resource(url) {
  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;
}

req.overrideMimeType 重写了默认的 MIME 类型,主要是告诉浏览器不要解析数据,直接返回未处理的字节码

var filestream = load_binary_resource(url);
var abyte = filestream.charCodeAt(x) & 0xff; // 扔掉的高位字节(f7)

上例从请求回来的二进制数据中得到偏移量为x处的字节.有效的偏移量范围是 0 到 filestream.length - 1

本文为原创,未经授权,禁止任何媒体或个人自媒体转载
商业侵权必究,如需授权请联系[email protected]
标签: Javascript html5