【问题标题】:Display count value in the mysql database table using handlebars in Nodejs project在Nodejs项目中使用把手显示mysql数据库表中的计数值
【发布时间】:2016-12-13 15:39:47
【问题描述】:

我有一个网页显示某些年级的申请数量。比如六年级、七年级和八年级的申请数量。我在六年级和七年级使用的函数如下:

function getGrade6Applicants(req, res, next) {
connection.query('SELECT COUNT(*) AS grade_6 FROM applications WHERE grade="Grade 6" ', function (err, rows, fields) {
    if (err) {
        return next(err);
    };
    req._applications = rows;
    return next();
});}

function getGrade7Applicants(req, res, next) {
connection.query('SELECT COUNT(*) AS grade_7 FROM applications WHERE grade="Grade 7" ', function (err, rows, fields) {
    if (err) {
        return next(err);
    };
    req._applications = rows;
    return next();
});}

然后我将这个函数用于我的 GET 请求,如下所示。如果它只是用于grade_6,它工作正常。 mysql 表的名称是“应用程序”。

/* GET dashboard page */
router.get('/dashboard', getGrade6Applicants, function (req, res, next) {
   res.render('admission/dashboard', {
       'applications': req._applications
   });
})

这给了我 mysql 数据库的应用程序表中 6 年级的应用程序数量。

我在我的 dashboard.handlebars 页面中使用它作为 {{grade_6}} 使用适当的 {{#if}} 和 {{#each}} 内置帮助程序。

问题是每当我想添加第二个功能来显示 7 年级的应用程序数量时,我只有 7 年级的应用程序。 6级没有显示。这是我用于多个值的 GET 请求:

/* GET dashboard page */
router.get('/dashboard', getGrade6Applicants, getGrade7Applicants, function (req, res, next) {
   res.render('admission/dashboard', {
       'applications': req._applications
   });
})

【问题讨论】:

  • 您的每个 getGradeXApplications 都会覆盖相同的变量来存储它们的结果 - req._applications。
  • 那么如何不覆盖并获得不同的结果以便我可以在网页上使用它呢?
  • 几种方式:使用不同的变量名,压入数组等
  • 我想我需要你解释一下如何使用不同的变量。
  • 当然。您可以将req._applications6 = rows 用于grade6 数据,将req._applications7 = rows 用于grade7 数据等。然后在您的代码中将{ 'applications6': req._applications6, 'applications7': req._applications7 } 发送到仪表板渲染器。

标签: mysql node.js http get handlebars.js


【解决方案1】:

这是我的有效解决方案:

我的路由器 js 文件:

router.get('/dashboard', getGrade7Applicants, getGrade8Applicants, function (req, res, next) {
res.render('admission/dashboard', {
    applications: {
            'grade7': req._applications7[0],
            'grade8': req._applications8[0],
    }

});
});

这里是html模板:

 {{#if applications}}
     {{#if applications.grade7}}
         {{applications.grade7.grade7}}
      {{/if}}
     .......
   {{#if applications.grade8}}
         {{applications.grade8.grade8}}
      {{/if}}
{{/if}}

【讨论】:

    猜你喜欢
    • 2017-12-08
    • 1970-01-01
    • 2020-07-09
    • 1970-01-01
    • 2018-05-14
    • 1970-01-01
    • 2021-08-12
    • 2018-05-30
    • 1970-01-01
    相关资源
    最近更新 更多