MongoDB 商品数据表格展示:前后端代码实现
本文提供完整的 Node.js 后端代码和 jQuery 前端代码,实现从 MongoDB 数据库中获取商品 ID、价格、数量等信息,并以表格形式动态展示在网页上。
前端代码
<table>
<thead>
<tr>
<th>ID</th>
<th>价格</th>
<th>数量</th>
</tr>
</thead>
<tbody id='productTableBody'>
</tbody>
</table>
<script>
$(document).ready(function() {
$.ajax({
url: '/getProducts',
type: 'GET',
dataType: 'json',
success: function(data) {
$.each(data, function(index, product) {
var html = '<tr>';
html += '<td>' + product.id + '</td>';
html += '<td>' + product.price + '</td>';
html += '<td>' + product.quantity + '</td>';
html += '</tr>';
$('#productTableBody').append(html);
});
}
});
});
</script>
后端代码
const express = require('express');
const app = express();
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
const dbName = 'mydb';
app.get('/getProducts', function(req, res) {
MongoClient.connect(url, function(err, client) {
if (err) throw err;
const db = client.db(dbName);
const collection = db.collection('products');
collection.find().toArray(function(err, products) {
if (err) throw err;
res.json(products);
client.close();
});
});
});
app.listen(3000, function() {
console.log('Server listening on port 3000');
});
这段代码使用了 Express 和 MongoDB 的 Node.js 库。当前端发送 GET 请求到 /getProducts 路径时,后端会连接到 MongoDB 数据库,查询所有商品信息,并返回 JSON 格式的数据。前端会通过 AJAX 请求从后端获取数据,并使用 jQuery 动态生成表格。
原文地址: https://www.cveoy.top/t/topic/nME5 著作权归作者所有。请勿转载和采集!