簡體   English   中英

AJAX - 將返回的八位字節流轉換為類型化數組 (Float64Array)

[英]AJAX - Convert returned octet-stream to typed array (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 中沒有控制台錯誤,所以我很難真正確定我遺漏了什么。 我想先將data轉換為ArrayBuffer嗎? 我在十六進制編輯器中查看了data ,並確認返回的字節流是具有正確值的正確雙精度數組(64 位小端)。

Float64Array構造函數需要一個ArrayBuffer參數。 為了讓瀏覽器這樣解釋響應,請嘗試

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

使用Response.arrayBuffer()方法的fetch API 等價物是這樣的

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM