javascript - 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 中没有控制台错误,所以我很难确定我所缺少的内容。我想转换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"
}
})
fetch
API等价物是这样的,使用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)
}
}
推荐阅读
- c# - 在 IIS 中部署 Silverlight 应用程序发生错误 ERROR Code 2105 Failed to load Silverlight Prerequisites
- java - Spark 作业需要很长时间才能使用 wholeTextFiles 从 HDFS 文件中读取数据
- xcode - 修改 USDZ 文件 Shading 纹理
- python - 动画图“列表”对象没有属性“set_ydata”
- ios - 最初打开 iOS13+ 的应用程序后更新/更改根视图控制器
- php - 在 WordPress 上使用 jQuery
- android - 手动设置 Firebase Firestore 缓存
- javascript - 当我坚持我正在使用的事件时,为什么 setTimeout 不起作用?
- javascript - 用户登录 React Native 后如何获取网站
- android-studio - 如何将窗口(桌面)添加到 android studio 设备