Ajax按钮启动每个按钮,而不仅仅是所选按钮

时间:2015-06-03 20:29:57

标签: javascript jquery ajax django django-views

我想创建一个ajax按钮,一旦点击,该项目就会被用户“购买”。购买商品后,按钮的文字将会更新。

该功能有效,但就好像我点击了每个按钮,而不仅仅是一个按钮。

例如,我有两件商品要购买。如果我在第1项上单击“购买”,则第1项和第2项都会通过,就像它们都被购买一样。我怎么做到这一点只买了第1项?

提前谢谢!

views.py:

def product_purchase(request):
    if request.is_ajax() and request.POST:
        user = request.user
        product_pk = request.POST.get('product_pk', False)
        product = get_object_or_404(Product, pk=product_pk)

        purchased, created = Product.objects.get_or_create(pk=product_pk)

        try:
            user_purchased = Product.objects.get(pk=product_pk, buyers=user)
        except:
            user_purchased = None

        if user_purchased:
            purchased.buyers.remove(user)
            purchased.save()
            user_has_purchased = False
        else:
            purchased.buyers.add(user)
            purchased.save()
            user_has_purchased = True

        data = {
            "user_has_purchased": user_has_purchased,
        }
        new_data = json.dumps(data)
        return HttpResponse(new_data, content_type='application/json')
    else:
        raise Http404

HTML:

{% for product in products %}
    <input class="btn btn-default selector" product="{{ product.pk }}" value="{% if request.user.username in purchased.get_buyers %} Purchased {% else %} {{ product.cost }} points {% endif %}" type="button" />
{% endfor %}

的javascript:

$('.selector').click(function(e){
    e.preventDefault();
    var $selector = $(e.currentTarget);
    $.ajax({
        type: "POST",
        url: "{% url 'product_purchase' %}",
        data: {
            "product_pk": $(this).attr("product"),
            csrfmiddlewaretoken: "{{ csrf_token }}",
        },
        dataType: "json",
        success: function(data) {
            if (data.user_has_purchased) {
                $selector.val("Purchased");
            } else {
                $selector.val("{{ product.cost }} points");
                }
        },
        error: function (rs, e) {
            alert('Sorry, there was an error.');
        }
    });
});

1 个答案:

答案 0 :(得分:0)

我向大家道歉。解决方案是我输入的值。更正是将purchased.get_buyers更改为product.get_buyers

谢谢大家的帮助!