【发布时间】: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