【问题标题】:Returning Multiple SQL Results to .handlebars using Express使用 Express 将多个 SQL 结果返回到 .handlebars
【发布时间】: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


    【解决方案1】:

    您确定没有遗漏 page1.js 中的任何部分吗? 我很好奇为什么您的括号和花括号没有正确闭合时没有收到任何错误?

    例如:

     // 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();
    }
    

    您缺少一个 ) 来关闭查询,以及一个 } 来关闭函数

    【讨论】:

      猜你喜欢
      • 2015-05-25
      • 1970-01-01
      • 2015-05-17
      • 2023-02-06
      • 2012-10-28
      • 2011-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多