我是node.js的新手,我想知道如何使用mysql值填充页面加载时的选择菜单。我正在使用nodejs,expressjs和jade / pug。我无法在Google中找到任何解决方案。

玉锉:-

block sale
 form(action = "/get_sale", method = "GET")
  select(id="cbosale", name="cbosale", class="custom-select custom-select-sm")
   each sale in ["24", "34"]
    option(value="#{sale}") #{sale}


App.js文件:-

app.get('/get_sale', function(req, res){
 db.connect(function(err){
  db.query("SELECT DISTINCT(SaleNo), Season FROM tcatalogue",function(err, result, fields){
  Object.keys(result).forEach(function(key){
    var row = result[key];
    console.log(row.SaleNo)
  })
})
})
})


应该从app.js文件中获取值,而不是jade文件中的静态值。

最佳答案

当您尝试获取路由时,需要在数据库上触发选择查询,并将数据与render一起发送到pug:

app.get('/output',function(req,res,next){
   con.query("SELECT * FROM tableName", function (err, result, fields)
    {
    if (err)
      throw err;
    else
      res.render('output',{page_title:"Output",data:result});
   });
 });


现在,您的output.pug页面将使用数据生成,您可以将其填充为选择菜单的选项。

html
    head
        title= 'Output'
    body
      select
        each variable in data
        option(value=variable.saleNo)


在帕格中正确缩进代码。

09-30 17:46
查看更多