首页 > 解决方案 > AJAX - 将返回的八位字节流转换为类型化数组 (Float64Array)

问题描述

我无法弄清楚我在这里做错了什么。我正在尝试将从 AJAX 调用返回的二进制流转换为 JavaScript 中的双精度数组。一些代码:我的服务器 PHP 返回一个八位字节流(双精度数组):

while(logic_code)
{
  $binary .= pack('ddd*', item1, item2, item3);
}

header('Content-type: application/octet-stream');
header('Content-length: ' . strlen($binary));
http_response_code(200);
echo $binary;
exit;

在我的网页中,我有一个 AJAX 调用:

function getData() {
    $.ajax({
        type: 'GET',
        url:  '/my/rest/call/to/above/php/code',
        success: function(data) {
            doSomething(data);
        },
        error: function(data, status, error) {
        }
    });
}

然后我的函数用于处理从其余调用返回的数据doSomething(data)

function doSomething(data) {
    // Some code here.
    
    var count = data.length / (8);  // Get number of DOUBLES
    var arr = new Float64Array(data, 0, count);

    console.log(arr);

    // Problem: 'arr' is undefined, or array of 0; but 'count' is non-zero.

    // More code here.
}

我面临的问题是Float64Array似乎没有将我的数据转换为数组。我得到的大小为零且未定义,而count数字很大。Chrome 中没有控制台错误,所以我很难确定我所缺少的内容。我想转换dataArrayBuffer第一个吗?我data在十六进制编辑器中查看并确认返回的字节流是具有正确值的正确双精度数组(64 位小端)。

标签: javascriptphpjqueryarraysajax

解决方案


构造Float64Array函数需要一个ArrayBuffer参数。为了让浏览器这样解释响应,请尝试

$.ajax({
  url: "/my/rest/call/to/above/php/code",
  method: "GET",
  success: doSomething,
  error: (_, ...err) => console.error(...err),
  xhrFields: {
    responseType: "arraybuffer"
  }
})

fetchAPI等价物是这样的,使用Response.arrayBuffer()方法

async function getData() {
  try {
    const res = await fetch("/my/rest/call/to/above/php/code")
    if (!res.ok) {
      throw new Error(`${res.status}: ${await res.text()}`)
    }
    
    doSomething(await res.arrayBuffer())
  } catch (err) {
    console.error(err)
  }
}

推荐阅读