【发布时间】:2021-04-20 21:02:47
【问题描述】:
我正在尝试通过发出 AJAX http 请求从我的 api 中获取我的数据。请求的数据采用 JSON 格式。我无法真正理解应该以什么格式格式化数据以便从柱形图中读取数据。例如,如果我尝试记录对象thedata.y 的属性,那么我得到未定义。如果我复制整个数组而不是 dataPoints 处的数据,那么它可以完美运行,但不仅仅是输入数组名称。我究竟做错了什么?提前致谢
前端脚本
doctype html
html(lang='en')
head
meta(charset='utf-8')
meta(name='viewport', content='width=device-width, initial-scale=1')
script( src="https://canvasjs.com/assets/script/canvasjs.min.js")
script(src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous")
body
script.
var thedata=[];
$.getJSON("http://localhost:3000/catalog/statistics/BookingsPerResource", function (items) {
$.each(items, function (index, value) {
thedata.push({
label: value.label,
y: value.y
})
});
console.log(thedata)
})
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
theme: "light1", // "light2", "dark1", "dark2"
animationEnabled: false, // change to true
title: {
text: "Basic Column Chart"
},
data: [
{
// Change type to "bar", "area", "spline", "pie",etc.
type: "column",
dataPoints: thedata
}
]
});
chart.render();
}
div(id="chartContainer" style="height: 370px; width: 100%;")
h3=thedata
后端脚本
exports.loadStats= async function (req,res,next){
try {
var BooksperResource = await resource.aggregate().project(
{
"label":"$name",
y:{$cond:{if:{$isArray:"$reservation"},
then:{$size:"$reservation"},
else:0}
},
_id:0
}
).limit(10)
} catch (error){
return next(error)
}
console.log(JSON.parse(JSON.stringify(BooksperResource)))
res.send(JSON.parse(JSON.stringify(BooksperResource)))
};
exports.displayStats= async function (req,res,next){
res.render('statsDash');
}
来自 AJAX 调用的 JSON 响应
[
{ label: 'Sillicon Waffer Tool', y: 2 },
{ label: 'Photolithography Laboratory', y: 2 },
{ label: 'Resource', y: 1 },
{ label: '" SELECT * FROM users', y: 0 }
]
【问题讨论】:
标签: javascript ajax express canvas charts