【发布时间】:2021-06-23 02:56:16
【问题描述】:
我之前从未使用过带有 nodejs 和 ejs 的 json,所以请原谅我缺乏知识。我能够从 json 生成项目列表,但是当我按下下拉列表进行排序时,除了基于下面的 ejs 按 id 进行默认排序之外,它没有显示任何输出。我是不是连接错了json?
nodejs
router.get('/product', (req,res) =>{
fs.readFile('items.json', function (error, data) {
if (error) {
res.status(500).end()
} else {
res.render('product.ejs', {
user: req.user,
stripePublicKey: stripePublicKey,
items: JSON.parse(data)
})
}
})
})
ejs
<select id="sortMed" onChange="getSelectValue()">
<option onClick="defaultSorting()">Default Sorting</option>
<option onClick="sortingbyPrice()">Sorting by price</option>
<option onClick="sortingbyAlphabet()">Sorting by alphabet</option>
</select>
<div class="row">
<div class="col-4">
<div class="shop-items" id="output">
<% items.medicine.forEach(function(item){ %>
<div class="shop-item" data-item-id="<%= item.id %>">
<span class="shop-item-title"><%= item.name %></span>
<img class="shop-item-image" src="../assets/img/<%= item.imgName %>">
<div class="shop-item-details">
<span class="shop-item-price">$<%= item.price / 100 %></span>
<button class="btn btn-primary shop-item-button" type="button">ADD TO CART</button>
</div>
</div>
<% }) %>
</div>
</div>
</div>
javascript
function sortingbyPrice(){
console.log("Sorting price")
const itemsJson = JSON.parse(data)
$.getJSON('items.json', function(data) {
return sorted = items.medicine.sort((medA, medB) => medA.price - medB.price);
});
}
items.json
{
"medicine": [
{
"id": 1,
"name": "Bioderma",
"price": 5000,
"imgName": "product_01.png"
},
{
"id": 2,
"name": "Chanca Piedra",
"price": 2300,
"imgName": "product_02.png"
},
{
"id": 3,
"name": "Umcka",
"price": 4000,
"imgName": "product_03.png"
},
{
"id": 4,
"name": "CetylPure",
"price": 8700,
"imgName": "product_04.png"
},
{
"id": 5,
"name": "CLACORE",
"price": 5600,
"imgName": "product_05.png"
},
{
"id": 6,
"name": "POO-POURRI",
"price": 6800,
"imgName": "product_06.png"
},
{
"id": 7,
"name": "Ibuprofen",
"price": 6800,
"imgName": "product_07.png"
}
]
}
【问题讨论】:
-
你是如何在 sortbyPrice() 中读取 JSON 文件的?
-
问题更像是我能够根据教程的学习在 ejs 中显示来自 json 的列表,但我不知道如何将 json 文件连接到 ejs 进行排序。我不认为是通过测试 console.log 阅读它
-
$.getJSON 中的返回没有任何好处。在那里你需要用新数据填充你的组件。
标签: javascript node.js json ejs