使用nodejs在html页面上显示SQLServer查询结果

时间:2019-10-01 19:06:49

标签: javascript html node.js

nodejs的新手我已经设置了服务器,并且我正在运行查询并将其显示为json。但是我希望此json信息显示在html的表中。我将在下面包含一些代码。

//Connection String parameters 

sql.connect(sqlConfig,函数(req,res){

app.get("/reportStock", (req, res) => {
  var request = new sql.Request();
  request.query("select * from Products", function (err, resu) {
    res.json(resu.recordset);
    console.log(resu)

    var someData = JSON.stringify(res.recordsets);
    console.log(someData);
    res.render(__dirname + "/views/northwind.html", {
      fullList: someData
    });
  });
 });
}); // End of SQL Connect Statement

所以,如果我导航到localhost:8100 / reportStock,我会得到:

[{"ProductID":1,"ProductName":"Chai","SupplierID":1,"CategoryID":1,"QuantityPerUnit":"10 boxes x 20 
bags","UnitPrice":29700,"UnitsInStock":39,"UnitsOnOrder":0,"ReorderLevel":10,"Discontinued":false}, 

HTML:

 <h1> Products</h1>
        <h1>Pick one here please</h1>
        <h2> <%- fullList[0].ProductID %> </h2>
        <h2> <%- fullList[1].ProductName %> </h2>
        <div id='d1'></div>


<script>
var theFullList = <%-fullList%>;

for (var i=0;i<995;i++) {

    document.getElementById("d1").innerHTML += theFullList[i].ProductID + " - "
    document.getElementById("d1").innerHTML += theFullList[i].ProductName + "<br>"
}
</script>

任何人都可以分享一些html / javascript来说明如何将Json结果从/ reportStock中获取到我的常规html页面之一中,并将其显示为表格吗?

1 个答案:

答案 0 :(得分:0)

您可以使用javascript,ajax从网址中获取数据并显示为表格。

这里我仅将JQuery用于附加数据(也可以使用普通的javascript)

<html>
    //... meta tags goes here
    <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
    <script>
       (async () => { // if you want to use await your immediate parent function should be async
          let response = await fetch('http://<your domain>//reportStock'); // Fetch data
          let data = await response.json(); // Convert to JSON
          data.forEach(_d => { // Loop through data and append to table, Here I'm just using ProductID for reference. 
             let tr = '';
             tr += `<td> ${_d.ProductID} </td>`
             $('#data-table').append(tr);
          });
       }
    </script>
    <body>
        <table id="data-table">
           <th> Headers goes here </th>
        </table>
    </body>
</html>