How to write a jinja for loop inside a javascript function

问题描述 投票:0回答:1
javascript python flask jinja2 cart
1个回答
0
投票

看起来你试图在你的函数中混合 JavaScript 和 Jinja 模板语法,这是无效的。 Jinja 是一种用于 Flask 或 Django 框架的服务器端模板语言,而 JavaScript 是一种在浏览器中执行的客户端语言。

假设您使用的是 Flask,您可以按如下方式修改您的函数以获取购物车项目计数并更新购物车图标:

function updateCartIcon() {
  var cartCount = document.getElementById('cart-count');
  var itemCount = 0;
  fetch('/get_cart_items_count') // Send a GET request to the server to get the cart items count
    .then(response => response.json()) // Parse the JSON response from the server
    .then(data => {
      itemCount = data.count; // Update the item count with the response data
      cartCount.innerText = itemCount; // Update the cart icon
    });
}

然后,在您的 Flask 应用程序中,您可以创建一个路由

/get_cart_items_count
返回购物车项目计数作为 JSON 响应:

from flask import jsonify

@app.route('/get_cart_items_count')
def get_cart_items_count():
    count = 0
    if current_user.is_authenticated:
        count = current_user.cart_items.count()
    return jsonify({'count': count})

此路由将返回一个 JSON 响应,其中包含当前经过身份验证的用户的购物车商品的

count
updateCartIcon()
函数向该路由发送 GET 请求,解析 JSON 响应,并使用商品计数更新购物车图标。

© www.soinside.com 2019 - 2024. All rights reserved.