【发布时间】:2020-03-13 08:50:14
【问题描述】:
我是非常 Express 和 Node.js 的新手,我很好奇如何将多个 SQL 结果返回到页面元素。
这可能是一个直截了当的问题,但我不知道如何继续,非常感谢任何帮助。
所以,我有以下page1.js 文件:
module.exports = function(){
var express = require('express');
var router = express.Router();
// Get the results of the first SQL statement
function getMyTable(res, mysql, context, complete){
mysql.pool.query("SELECT * from MyTable", function(error, results){
if(error){
res.write(JSON.stringify(error));
res.end();
}
context.page1table = results;
complete();
}
// Get the results of the second SQL statement
function getMyList(res, mysql, context, complete){
mysql.pool.query("SELECT DISTINCT class from MyTable", function(error, results){
if(error){
res.write(JSON.stringify(error));
res.end();
}
context.page1list = results;
complete();
}
// Return to page
router.get('/',function(req,res){
var callbackCount = 0;
var context = {};
var mysql = req.app.get('mysql');
getMyTable(res,mysql,context,complete);
getMyList(res,mysql,context,complete);
function complete() {
callbackCount++;
if(callbackCount >= 2){
res.render('page1',context);
}
}
}
}();
然后我有一个page1.handlebars 文件:
<form id = "list_class">
<fieldset>
<label> Classses:
<select name = "class_list" id = "class_list">
{{#each page1list}}
<option value = '{{class}}'>{{class}}</option>
{{/each}}
</select>
</label>
</fieldset>
</form>
<table class ="resultTable">
<tbody id = "tableBody">
{{#each page1table}}
<tr>
<td>{{name}}</td>
<td>{{class}}</td>
<td>{{id}}</td>
</tr>
{{/each}}
</tbody>
</table>
编辑:我应该注意page1table 的结果已显示,但page1list 的结果未显示,尽管在function getMyList() 中调用console.log(context.page1list); 确实会将预期列表打印到控制台。我错过了什么?
【问题讨论】:
标签: mysql node.js express handlebars.js router