如何将Django HTML模板内的商品数量span值与{{ el.id }}传递到Django视图
实现方案
方案1:隐藏输入框随表单同步提交(适合普通表单提交场景)
你可以在每个商品对应的区域添加隐藏输入框,JS修改数量时同步更新输入框的值,提交表单时数据会自动传给Django后端:
模板代码修改
在你现有的span标签下方新增隐藏输入框:
<span id="value{{ el.id }}">0</span> <!-- 新增隐藏输入框,name携带商品id,用于后端识别 --> <input type="hidden" id="input_{{ el.id }}" name="product_{{ el.id }}" value="0">
修改你的JS逻辑,同步更新隐藏输入框的值:
$(function(){ var valueElement = $('#value{{ el.id }}'); var inputElement = $('#input_{{ el.id }}'); function incrementValue(e){ var newVal = Math.max(parseInt(valueElement.text()) + e.data.increment, 0); valueElement.text(newVal); // 同步更新隐藏输入框的值 inputElement.val(newVal); return false; } $('#plus{{ el.id }}').bind('click', {increment: 1}, incrementValue); $('#minus{{ el.id }}').bind('click', {increment: -1}, incrementValue); });
在form表单末尾添加提交按钮:
<button type="submit">确认售出商品</button>
Django后端接收逻辑
def product_sell(request): if request.method == "POST": # 遍历POST参数筛选商品数据 sell_data = {} for k, v in request.POST.items(): if k.startswith("product_"): # 拆分获取商品id和对应售出数量 product_id = k.split("_")[1] quantity = int(v) if quantity > 0: sell_data[product_id] = quantity # 此处执行你的商品售出业务逻辑 # ... return render(request, "你的模板路径.html")
方案2:AJAX异步提交(适合无需页面刷新的场景)
如果需要不刷新页面完成提交,可以通过AJAX主动收集所有商品的id和数量传给后端:
前端逻辑
首先移除循环内的重复JS代码,在页面底部统一编写通用逻辑:
<!-- 在form表单末尾添加AJAX提交按钮 --> <button type="button" id="ajax_submit">确认售出商品</button> <script> $(function(){ // 通用数量加减逻辑 $("a[id^='plus']").click(function(){ const id = $(this).attr("id").replace("plus", ""); const valEl = $("#value" + id); valEl.text(Math.max(parseInt(valEl.text()) + 1, 0)); return false; }); $("a[id^='minus']").click(function(){ const id = $(this).attr("id").replace("minus", ""); const valEl = $("#value" + id); valEl.text(Math.max(parseInt(valEl.text()) - 1, 0)); return false; }); // AJAX提交逻辑 $("#ajax_submit").click(function(){ const post_data = { "csrfmiddlewaretoken": $("input[name='csrfmiddlewaretoken']").val(), "products": {} }; // 收集所有商品的id和数量 $("span[id^='value']").each(function(){ const id = $(this).attr("id").replace("value", ""); const num = parseInt($(this).text()); if(num > 0) post_data.products[id] = num; }); // 发送请求到后端 $.post("/你的后端接口地址/", post_data, function(res){ if(res.code === 0) alert("商品售出成功"); else alert("操作失败:" + res.msg); }); }); }) </script>
Django后端接收逻辑
import json from django.http import JsonResponse def product_sell_ajax(request): if request.method != "POST": return JsonResponse({"code": 1, "msg": "请求方式错误"}) try: products = json.loads(request.POST.get("products", "{}")) for product_id, quantity in products.items(): # 执行商品售出业务逻辑 # ... return JsonResponse({"code": 0, "msg": "操作成功"}) except Exception as e: return JsonResponse({"code": 1, "msg": str(e)})
内容的提问来源于stack exchange,提问作者Олег Щербина
相关产品推荐
相关产品推荐

