[英]AJAX - Convert returned octet-stream to typed array (Float64Array)
I cannot figure out what I'm doing wrong here.我无法弄清楚我在这里做错了什么。 I'm trying to convert a binary stream, returned from an AJAX call, to an array of doubles in JavaScript.我正在尝试将从 AJAX 调用返回的二进制流转换为 JavaScript 中的双精度数组。 Some code: My server PHP returns an octet-stream (array of doubles):一些代码:我的服务器 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;
In my webpage I have an AJAX call:在我的网页中,我有一个 AJAX 调用:
function getData() {
$.ajax({
type: 'GET',
url: '/my/rest/call/to/above/php/code',
success: function(data) {
doSomething(data);
},
error: function(data, status, error) {
}
});
}
And then my function for processing the returned data from the rest call doSomething(data)
:然后我用于处理从其余部分返回的数据的函数调用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.
}
The issue I'm facing is that Float64Array
doesn't seem to be converting my data to an array.我面临的问题是Float64Array
似乎没有将我的数据转换为数组。 I get a size of zero and undefined while count
is a large number.我得到的大小为零且未定义,而count
是一个大数字。 There are no console errors in Chrome so I'm having a hard time really pinning down what I'm missing. Chrome 中没有控制台错误,所以我很难真正确定我遗漏了什么。 Am I suppose to convert data
to an ArrayBuffer
first?我想先将data
转换为ArrayBuffer
吗? I have looked at data
in a hex editor and confirmed the returned byte stream is the correct array of doubles (64-bit little endian) with correct values.我在十六进制编辑器中查看了data
,并确认返回的字节流是具有正确值的正确双精度数组(64 位小端)。
The Float64Array
constructor expects an ArrayBuffer
argument. Float64Array
构造函数需要一个ArrayBuffer
参数。 In order to have the browser interpret the response as such, try为了让浏览器这样解释响应,请尝试
$.ajax({
url: "/my/rest/call/to/above/php/code",
method: "GET",
success: doSomething,
error: (_, ...err) => console.error(...err),
xhrFields: {
responseType: "arraybuffer"
}
})
The fetch
API equivalent would be like this, using the Response.arrayBuffer()
method使用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.