我有一个名为 Gerechten 的表,其中包含以下列:id、gerecht、beschrijving、categorie、prijs、url 和 sterren。在这个表中我有很多行,所以我在html脚本中使用了jinja循环来循环每一行并显示它们,每个div都是它自己的食物,所以我在每个div的底部都有一个购买按钮。我想知道如何获取所购买餐食的 ID 并在 JavaScript 脚本中使用它。这样我就可以将其添加到购物车中。 这是我在烧瓶中的桌子:
class Gerechten(db.Model):
__bind_key__ = 'gerechten'
__tablename__ = 'gerechten'
id = db.Column(db.Integer, primary_key=True)
gerecht = db.Column(db.String(80), index=True, unique=True)
beschrijving = db.Column(db.String(80), index=True)
categorie = db.Column(db.String(80), index=True)
prijs = db.Column(db.Integer, index=True)
sterren = db.Column(db.Integer, index=True)
url = db.Column(db.String(120), index=True)
db.create_all()
这是我的 jinja 脚本:
{% for gerecht in gerechten %}
<div class="Gerechtdiv">
<img src={{gerecht.url}} class="gerechtimg">
<h3 class="GerechtTitel">{{gerecht.gerecht}}</h3>
<p class ="GerechtBeschrijving">{{gerecht.beschrijving}}</p>
<div class ="BottomGerechtDiv">
<p style="font-size: 17px;"><b>€{{gerecht.prijs}}</b></p>
<p>{{gerecht.sterren}}★</p>
</div>
<button class="button" onclick=""><span>Voeg toe aan winkelwagen</span></button>
</div>
{% endfor %}```
I havent tried anything yet, cause i just cant figure it out
要实现此目的,您可以修改 HTML 和 JavaScript,以在单击“Voeg toe aan winkelwagen”按钮时捕获餐食的 ID。具体方法如下:
单击按钮时,将餐食 ID 作为参数传递给 JavaScript 函数。 定义一个 JavaScript 函数,用于接收 id 参数并执行必要的操作,例如将餐食添加到购物车。 这是修改后的代码:
function addToCart(id) {
// You can perform any actions here, such as adding the id to the cart
console.log("Added meal with id: " + id + " to the cart");
// If you're using AJAX, you can send the id to the server for further processing
// For example:
/*
$.ajax({
url: '/add_to_cart',
type: 'POST',
data: { 'id': id },
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
*/
}
{% for gerecht in gerechten %}
<div class="Gerechtdiv">
<img src={{gerecht.url}} class="gerechtimg">
<h3 class="GerechtTitel">{{gerecht.gerecht}}</h3>
<p class ="GerechtBeschrijving">{{gerecht.beschrijving}}</p>
<div class ="BottomGerechtDiv">
<p style="font-size: 17px;"><b>€{{gerecht.prijs}}</b></p>
<p>{{gerecht.sterren}}★</p>
</div>
<!-- Pass the gerecht.id to the JavaScript function -->
<button class="button" onclick="addToCart({{ gerecht.id }})"><span>Voeg toe aan winkelwagen</span></button>
</div>
{% endfor %}
在此代码中:
单击按钮时,我们将餐食 ID 作为参数传递给 addToCart JavaScript 函数。 您可以将 addToCart 函数中的 console.log 语句替换为将餐食添加到购物车时要执行的任何操作,例如向服务器发出 AJAX 请求以将餐食添加到购物车。 如果您发出 AJAX 请求,请记住包含必要的库(例如 jQuery)。