Afshin Mehrabani
Afshin Mehrabani

Reputation: 34929

TypeError: Type error when working with typed arrays

When I trying to convert my XHR response to TypedArray in JavaScript, I get:

TypeError: Type error

This is my server-side code (ASP.NET Web Form):

public partial class _Default : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        int number = 4;
        Response.BinaryWrite(BitConverter.GetBytes(number));
        Response.End();
    }
}

And Here my client-side code:

xhr.open("GET", "http://localhost:6551/Default.aspx", false);  
xhr.overrideMimeType("text/plain; charset=x-user-defined");  
xhr.send(null);
var sss = new DataView(xhr.response);

Also when I try to convert the xhr.response with Int16Array I get this error:

RangeError: Size is too large (or is negative).

What's wrong with my code?

Upvotes: 2

Views: 334

Answers (1)

Afshin Mehrabani
Afshin Mehrabani

Reputation: 34929

Ok I find out the problem, I should use xhr.responseType = "arraybuffer"; in the XHR request and the code finally is:

var xhr = new XMLHttpRequest();

xhr.open("GET", "http://localhost:6551/Default.aspx", true);
xhr.responseType = "arraybuffer"; 
xhr.onload = function(e) {
  var arraybuffer = xhr.response; // not responseText
  console.log(new Uint32Array(arraybuffer));
}
xhr.send();

More detail: https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest

Thanks for your help @MarcoK.

Upvotes: 2

Related Questions