【问题标题】:Canvas.js fetch data from RESTful APICanvas.js 从 RESTful API 获取数据
【发布时间】: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


    【解决方案1】:

    所以我在搜索更多后找到了解决方案。要解决这个问题,只需更改前端脚本的结构。应该将 ajax 代码放在 window.onload 构造函数内,然后在 $.getJSON 内必须放置图表构造函数。我知道它很畏缩,但我不明白为什么要这样说

    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.
    
                window.onload = function () {
                    var thedata = [];var  i=0;
                    $.getJSON("http://localhost:3000/catalog/statistics/BookingsPerResource", function (items) {
                        $.each(items, function (index, value) {
                            thedata.push({
                                label: value.label,
                                y: parseInt(value.y)
                            })
                        });
    
                        console.log(thedata)
                        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();
                    })
    

    【讨论】:

      猜你喜欢
      • 2018-08-24
      • 1970-01-01
      • 2015-09-10
      • 2021-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-07
      • 1970-01-01
      相关资源
      最近更新 更多