使用nodejs在html页面上显示SQLServer查询结果
对nodejs的新手,我已经设置了服务器,正在运行查询并显示为json。但是我希望此json信息显示在html的表中。我将在下面包含一些代码。
//Connection String parameters
sql.connect(sqlConfig, function (req, res) {
app.get("/reportStock", (req, res) => {
var request = new sql.Request();
request.query("select * from Products", function (err, resu) {
res.json(resu.recordset);
});
});
因此,如果我导航到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 / javascript来说明如何将Json结果从/ reportStock中获取到我的常规html页面之一中,并将其显示为表格吗?
回答如下:您可以使用javascript从URL获取数据并显示为表格。
这里我仅将JQuery用于附加数据(也可以使用普通的javascript)
<html>
//... meta tags goes here
<script src="https://code.jquery/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>