有道云笔记:有道云笔记
Decoder.js: 有道云笔记
1、首先在请求的时候进行设置response返回为字节数组
url: "https://sll.ddbddb.com/getDmsData", method: "GET", responseType: 'arraybuffer', // 设置response返回为字节数组 data: { token: app.globalData.userToken, // token: options.token, machineSllId: sllId },
2、将返回的 字节数组丢进uint8数组里
备注:Uint8Array属于自带对象,new Uint8Array 进行实例化。
success: (res) => { // 字节数组丢进uint8数组里 let unit8Arr = new Uint8Array(res.data);
3、确保引入GBK编码 import Decoder from "路径/encode/Decoder";
import Decoder from "../../encode/Decoder";
4、进行 GBK转UTF-8
var jsonStr = Decoder.GBKHexstrToString(Decoder.binaryarrayToHexstr(unit8Arr));
5、字符串转Object -> JSON
data为可用数据
// 字符串转Object -> JSON let data = JSON.parse(jsonStr);
完整代码,因为是小程序所以是wx.request,JS其他地方可能需要微调使用。
wx.request({ url: "https://sll.ddbddb.com/getDmsData", method: "GET", responseType: 'arraybuffer', // 设置response返回为字节数组 data: { token: app.globalData.userToken, machineSllId: sllId }, success: (res) => { // 字节数组丢进uint8数组里 let unit8Arr = new Uint8Array(res.data); var jsonStr = Decoder.GBKHexstrToString(Decoder.binaryarrayToHexstr(unit8Arr)); // 字符串转Object -> JSON let data = JSON.parse(jsonStr); var curr_channels = {}; var not_channels = data.channels; // 循环进行重组数据 for (let i = 0; i < not_channels.length; i++) { const not_value = not_channels[i]; curr_channels[i] = { channelName: not_value.channelName, alarmTag: not_value.alarmTag }; } console.log(curr_channels); //输出打印看是否有数据 let that = this; that.setData({ // channels: res.data.channels,//赋值 channels: curr_channels, machineSllId: sllId }); } })