gpt4 book ai didi

javascript - 尝试从服务器解析并转换 JSON

转载 作者:太空宇宙 更新时间:2023-11-04 15:50:37 25 4
gpt4 key购买 nike

我正在尝试接收 JSON 字符串并将其输入到 canvasJS 图表中。我很难弄清楚如何将我的字符串转换为正常工作。这是我正在尝试的方法,但不起作用:

function loadGraph(serialNum){

$.post("../Modules/LoadGraph_Mod/load_graph_mod.php",
{
submit: 'loadGraph',

serial:serialNum


},
function(data,status){

newDataPoints=data;

});

var chart = new CanvasJS.Chart("chartContainer",
{
interactivityEnabled: true,
zoomEnabled: true,
panEnabled: true,
backgroundColor:"#000",


axisX: { lineThickness: 1,
lineColor: "#333",
interval: 4

,
intervalType: "minutes",
valueFormatString: "h:mm",
labelFontColor: "#777"
},


axisY: { tickColor:"#333",
gridColor: "#222",
lineThickness: 1,
lineColor: "#333",
valueFormatString: "" ,
maximum: 100 },
data: [{
dataPoints : newDataPoints,
markerType: "none",
color: "#9c9a0c",
type: "area",
xValueType: "dateTime"

}]
});

chart.render();

}

我尝试过测试它,但直接插入我的服务器响应:

newDataPoints='[{"x":1483648595798,"y":62},{"x":1483648598843,"y":63},{"x":1483648601969,"y":64},{"x":1483648605088,"y":65},{"x":1483648779011,"y":0},{"x":1483648847224,"y":16}]';

这给了我错误:未定义不是一个对象。我尝试运行 JSON.parse 并最终出现错误,提示无法识别的标记“<”。

当我将字符串直接粘贴到图表中时,它会起作用,如下所示:

data: [{
dataPoints : [{"x":1483648595798,"y":62},{"x":1483648598843,"y":63},{"x":1483648601969,"y":64},{"x":1483648605088,"y":65},{"x":1483648779011,"y":0},{"x":1483648847224,"y":16},{"x":1483648860414,"y":17},{"x":1483648862560,"y":18},{"x":1483648865650,"y":19},{"x":1483648868773,"y":20}],
markerType: "none",
color: "#9c9a0c",
type: "area",
xValueType: "dateTime"

}]

所以我试图弄清楚如何转换从服务器返回的 JSON 字符串,使其在我的图表中正常工作。我将不胜感激任何帮助。谢谢。

最佳答案

如果您尝试从服务器发出简单的请求并返回 JSON 对象,我会执行以下操作

var http = require('http');
http.get(yourUrl, (res) => {
const statusCode = res.statusCode;

let error;
if (statusCode !== 200) {
error = new Error('Request Failed' + statusCode);
}

if (error) {
console.log(error.message);
}

let body = '';
res.on('data', (chunk) => {
//individual pre-processing here
body += chunk;
}).on('end', () => {
let parsedBody = JSON.parse(body);
//Whatever you want to do with the object
}).on('error', (err) => {
console.log(err);
});
});

关于javascript - 尝试从服务器解析并转换 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43146912/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com