TypeError:使用类型化数组时发生类型错误

TypeError: Type error when working with typed arrays

本文关键字:类型 错误 数组 类型化 TypeError      更新时间:2023-09-26

当我试图用JavaScript将XHR响应转换为TypedArray时,我得到:

TypeError:类型错误

这是我的服务器端代码(ASP.NET Web表单):

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

这里是我的客户端代码:

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);

此外,当我尝试用Int16Array转换xhr.response时,我会收到以下错误:

RangeError:大小太大(或为负数)。

我的代码出了什么问题?

好的,我发现了问题,我应该在XHR请求中使用xhr.responseType = "arraybuffer";,最终代码是:

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();

更多详细信息:https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest

感谢你的帮助@MarcoK。