简体   繁体   English

从 SQLite 获取数据作为数组并使用 HTML 中的 Chart.js 生成图表

[英]Get data from SQLite as an array and generate charts with the data using Chart.js in an HTML

I'm currently working on a web app, where I want to put some data visualization on one page.我目前正在开发一个 web 应用程序,我想将一些数据可视化放在一个页面上。 The data I use to generate the visual is from an SQLite database stored locally in my machine.我用来生成视觉效果的数据来自存储在我机器本地的 SQLite 数据库。 Based on the documentation of Chart.js , it will take an array and generate charts based on that, and the code is put in an HTML file under tag, so basically it is JavaScript code.根据Chart.js的文档,它将获取一个数组并基于该数组生成图表,并将代码放在标签下的 HTML 文件中,因此基本上是 JavaScript 代码。

Below is the code from Chartjs documentation I am using.下面是我正在使用的 Chartjs 文档中的代码。

 <canvas id="myChart" width="400" height="400"></canvas> <script> var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'], datasets: [{ label: '# of Votes', data: *there will be the data array from my SQLite*, backgroundColor: [ ], borderColor: [ ], borderWidth: 1 }] } }); </script>

Therefore, I need to get the data from my SQLite database, convert the field I want charts from to an array, and pass the array to the data field.因此,我需要从我的 SQLite 数据库中获取数据,将我想要图表的字段转换为数组,并将数组传递给数据字段。

So my question is, is it possible to do this?所以我的问题是,有可能做到这一点吗? I know some Node.js, thus I have no difficulties getting data from database with the help of require() and Sequelize.我知道一些 Node.js,因此在 require() 和 Sequelize 的帮助下从数据库中获取数据没有任何困难。 Yet I still find myself almost helpless when I want to do basically the same thing with JavaScript.然而,当我想对 JavaScript 做基本相同的事情时,我仍然发现自己几乎无能为力。 Or, is it possible if I get the data array ready using Node.js, then somehow let it pass the array to the HTML file?或者,是否可以使用 Node.js 准备好数据数组,然后以某种方式让它将数组传递给 HTML 文件?

Thanks!谢谢!

  • Edit: Below is the project structure编辑:下面是项目结构

 C:\USERS\XLYU0\VUE\PRACTICE\SQLITENODEJS\USER_AUTHEN | app.js | package-lock.json | package.json | +---config | auth.js | database.js | passport.js | +---models | CONTACT_TIME.js | USER.js | +---public | | bootstrap.css | | | +---css | | style.css | | | \---JS | sqlite.js | +---routes | contacts.js | index.js | services.js | statistics.js | uploads.js | users.js | \---views | contacts.ejs | dashboard.ejs | layout.ejs | layoutB.ejs | login.ejs | register.ejs | services.ejs | statistics.ejs | uploads.ejs | welcome.ejs | \---partials messages.ejs

The JS code for generating charts is in statistics.ejs, and I intend to put code that gets data from the database in JS/sqlite.js, though I suppose it'll be okay it goes to statistics.ejs as well as long as it is JavaScript.生成图表的 JS 代码在 statistics.ejs 中,我打算将从数据库中获取数据的代码放在 JS/sqlite.js 中,不过我想它可以放到 statistics.ejs 中,只要它是 JavaScript。

The SQLite file is stored somewhere else in my machine locally, and now I know how to connect to it by following instructions , and here is what I got for now. SQLite 文件本地存储在我机器的其他位置,现在我知道如何按照说明连接到它,这就是我现在得到的。

 var sqlite3 = require('sqlite3').verbose(); var db = new sqlite3.Database('../../../../../../database.db'); let reportingTag = []; let sql = `SELECT * FROM CONTACT_TIME`; db.all(sql, [], (err, rows) => { if (err) { throw err; } rows.forEach((row) => { reportingTag.push(row.reportingTag); }); console.log(reportingTag); }); // close the database connection db.close();

  • Edit: here is my current progress编辑:这是我目前的进展

 const express = require('express') const CONTACT = require('../models/CONTACT_TIME') const { render } = require('ejs') const router = express.Router() router.post('/', (req, res) => { CONTACT.findAll().then((contacttime) =>{ const context = { contextContactTime: contacttime.map(contacttime =>{ return{ id: contacttime.id, reportingTag: contacttime.reportingTag, } }) } let tags = [] context.contextContactTime.forEach((contact) =>{ tags.push(contact.reportingTag) }) res.send(tags) })}) router.get('/', (req, res) => res.render('statistics', { layout: 'layoutB' })) module.exports = router

I managed to send the data via Express.js router, yet I also want the template engine to render the page so I called res.render() below as well.我设法通过 Express.js 路由器发送数据,但我还希望模板引擎呈现页面,所以我在下面也调用了 res.render()。 Then it seems that the next step is to retrieve data on statistics.ejs.那么看来下一步就是检索statistics.ejs上的数据了。 Though I know how to display data on the page directly with ejs, I have trouble accessing data w/ JavaScript.虽然我知道如何使用 ejs 直接在页面上显示数据,但我无法使用 JavaScript 访问数据。 I need to do this since to generate charts with Chart.js I need to write some code between tag.我需要这样做,因为要使用 Chart.js 生成图表,我需要在标签之间编写一些代码。

Try to passing your data from tag body to tag script尝试将数据从标签正文传递到标签脚本

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
    <title>Documment</title>
</head>

<body>
    <div class="container">
        <canvas>
        </canvas>
        <p id="data" style="display:none"><%= value %></p>
    </div>
</body>
<script>
    // your data change to string
    let data = document.getElementById("data").innerText 
  
    let array = data.split(',')
</script>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM