d--b d--b - 1 year ago 115
Javascript Question

Why does the load event get called with ProgressEvent object?

I am trying to load binary data asynchronously in the browser:

var req = new XMLHttpRequest();
req.open("GET", "test.bin");
req.responseType = "arraybuffer";
req.addEventListener("load", function(res) {
var arrayBuffer = res.response; // Note: not oReq.responseText

but the load event that gets triggered has a
object that is a

Is that normal? I'm using chrome and reading the docs on MDN:

Why are the docs wrong? This should skip the progress events, no?

Answer Source

The docs aren't wrong and neither are you. The response object is a ProgressEvent from the load event. In order to get access to the response you need to point back to the original request (req) in your case.

var req = new XMLHttpRequest();
req.open("GET", "test.bin");
req.responseType = "arraybuffer";
req.addEventListener('load', function(res) {
  var arrayBuffer = req.response;

The ProgressEvent also has access to the source via currentTarget. For example:

req.addEventListener("load", function(res) {
  var arrayBuffer = res.currentTarget.response

And here is a fiddle: https://jsfiddle.net/08zm9urL/1/

Also Note:

You cannot access responseText when the responseType is arraybuffer. It must be either an empty string or text.

If responseType is set to anything other than the empty string or "text", accessing responseText will throw InvalidStateError exception.

From https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseText

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download