【问题标题】:Django: Javascript error with alert box displaying valuesDjango:警告框显示值的Javascript错误
【发布时间】:2021-03-25 16:50:21
【问题描述】:

我正在创建一个用作杂货店的 Web 应用程序。我设置它的方式是让客户可以进入网站,单击他们想要购买的商品,然后单击提交按钮购买这些商品。我遇到的问题是我的 Javascript 没有打印正确的值。在这两个地方,它都说未定义。我会在下面放一张图片以供参考。

views.py

def inventory(request):
    products = request.POST.getlist('products')
    for product in products:
        a = Post.objects.get(title=product)
        a.quantity = a.quantity -1
        a.save()
    print(products)
    return redirect('blog-home') 

home.html

{% extends "blog/base.html" %}
{% load static %}
{% block content %}
    <form action="{% url 'js' %}" method="POST" id="menuForm">
      {% for post in posts %}
        {% if post.quantity > 0 %}
            <article class="media content-section">
              <div class="media-body">
                <div class="article-metadata">
                  <a class="mr-2">{{ post.category }}</a>
                </div>
                <h2><a class="article-title" >{{ post.title }}</a></h2>
                <p class="article-content"> Price: ${{ post.Price }}</p>
                <p class="article-content"> Sale: ${{ post.Sale }}</p>
                <input type="checkbox" id="product_{{ post.id }}" value="{{ post.title }}" form="menuForm" name="products" > Inventory count: {{ post.quantity }}
              </input>
              </div>
            </article>
        {% else %}
        {% endif %}
      {% endfor %}
      <button id="btn" type="submit" form="menuForm">Confirm Purchase</button>
    </form>
<script src="{% static "JS/javascript.js" %}" type="text/javascript"></script>
{% endblock content %}

javascript.js

function getSelectedCheckboxValues(name) {
    const checkboxes = document.querySelectorAll(`input[name="${name}"]:checked`);
    let values = [];
    checkboxes.forEach((checkbox) => {
        values.push(checkbox.value);
    });
    return values, tPrice;

var price = 0;
var tPrice =0;
if (values=='Milk'){
    var MPrice = 3.99
    tPrice = price+MPrice;
}
if (values == 'Cheese'){
    var CPrice = 4.50
    tPrice = price + CPrice;
}
if (values == 'Yogurt'){
    var YPrice = 1.99
    tPrice = price + YPrice;
}
}

const btn = document.querySelector('#btn');
btn.addEventListener('click', (event) => {
    alert('You ordered: ' + getSelectedCheckboxValues('products')+
        '\nTotal Price: $'+ getSelectedCheckboxValues('tPrice'));
});

【问题讨论】:

  • 或许你可以在每一行后面加上console.log,看看问题出在哪里

标签: javascript python django django-forms django-templates


【解决方案1】:

首先,当您在警报中调用它们时,您将参数作为字符串传递给函数getSelectedCheckboxValues,这是完全错误的。 此外,您还直接将值列表与字符串进行比较,这是不可能的。您需要遍历列表,然后将不同元素与不同产品进行比较。我还建议创建一个对象而不是列表,并将产品名称作为键,将其价格作为值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-24
    • 2011-02-01
    相关资源
    最近更新 更多