weixin_33749242 2019-06-23 22:07 采纳率: 0%
浏览 33

Django使用Ajax

I am finish with my project using django but I want it to be a asynchronous so I use jquery and ajax but i am stuck right now, The problem is when I add a product in the cart all of the product fields in the table are having the same values but when I refresh it came back to their own values. Can any body help me with this, I am new in using ajax.

html

<div class="row mx-auto">
<div class="col-12 col-sm-12 col-md-12 col-lg-6 text-center">
<table class="table my_custom_table">
<thead class="my_custom_thead">
<tr>
    <th colspan="5">
        Your Cart Items
    </th>
</tr>
</thead>
<tbody>
{% for cart_item in cart_items %}
<tr class="cart-data">
    <td>
        <a href="{% url 'beer:product_detail' cart_item.product_format.product.id %}"><img src="{{ cart_item.product_format.product.photo_main.url }}" alt="" class="float-left rounded custom_image"></a>
    </td>
    <td class="text-left">
        <strong class="table-format">{{ cart_item.product_format.bformat }}</strong> 
        <br>
        SKU: {{ cart_item.product_format.id }}
        <br>
        Unit Price: ${{cart_item.product_format.price}}
        <br>
        Discount: {{cart_item.product_format.discount}}% 
        <br>
        Qty: <span class="cart-quantity">{{ cart_item.quantity }}</span>  x ${{ cart_item.product_format.price }}
    </td>
    <td class="text-primary">
        <strong> ${{ cart_item.sub_total|floatformat:2 }}</strong>
    </td>
    {% if cart_item.quantity < cart_item.product_format.in_stock %}

    <td class="btn-cart">
        <a href="{% url 'cart:add_cart' cart_item.product_format.id %}" class="custom_a add-to-cart" data-endpoint="{% url 'cart:add_cart' cart_item.product_format.id %}"><i class="fas fa-plus-circle custom_icon"></i></a><br><a href="{% url 'cart:cart_remove' cart_item.product_format.id %}" class="custom_a"><i class="fas fa-minus-circle custom_icon"></i></a><br><a href="{% url 'cart:full_remove' cart_item.product_format.id %}" class="custom_icon"><i class="fas fa-trash-alt custom_icon"></i></a>
    </td>
    {% else %}
    <td class="btn-cart">
        <br><a href="{% url 'cart:cart_remove' cart_item.product_format.id %}" class="custom_a"><i class="fas fa-minus-circle custom_icon"></i></a><br><a href="{% url 'cart:full_remove' cart_item.product_format.id %}" class="custom_icon"><i class="fas fa-trash-alt custom_icon"></i></a>
    </td>
    <td></td>
    {% endif %}
</tr>
{% endfor %}
</tbody>
</table>


</div>

script

<script>
$(document).ready(function(){
/* AJAX add to cart */ 
var cartAdd = $('.add-to-cart')
cartAdd.unbind('click').click(function(event) {
event.preventDefault();            
var thisLink = $(this)
var hrefEndpoint = thisLink.attr('data-endpoint')
var addCartMethod = "GET"
var linkData = thisLink.serialize();

var cartData = $('.cart-data')
var cartQuantity = cartData.find('.cart-quantity')
console.log(cartQuantity)

$.ajax({
  url: hrefEndpoint,    
  method: addCartMethod,                     
  data: linkData,

  success: function(data){ 
    var cartData = $('.cart-data')
    var cartQuantity = cartData.find('.cart-quantity') 
  cartData.find('.cart-quantity').text(data.quantity)             
    cartData = $('tbody tr').first()

    var currentPath = window.location.href
    if (window.location.href.indexOf('cart') != -1){
      updateCart()
    }
  },
  error: function(errorData){
    console.log('error')
    console.log('error', errorData)
  }
})
/* end of AJAX add to cart */ 
})
function updateCart(){
console.log('In current cart')
}

})
</script>```

views.py

added = True
if request.is_ajax():       
   subtotal = (product_format.price - product_format.price * 
   product_format.discount / 100) * cart_item.quantity
   productFormat = product_format.bformat
   json_data = {
        'added': added,
        'productFormat': str(productFormat),
        'quantity': cart_item.quantity,
        'discount': product_format.discount,
        'price': product_format.price,
        'subtotal': subtotal,
   }

   return JsonResponse(json_data) 

My expected output is that when you click the add link it will only change the value of the specific product.

  • 写回答

1条回答 默认 最新

  • weixin_33686714 2019-06-23 22:39
    关注

    Your .cart-unit-price selector (and others) in your ajax callback is targeting all rows with that class that are already present in the table. You would have to restrict the scope to a row, in this case to your row template.

    Let's say you have this row template as a string in the variable tpl.

    // Turn it into a jQuery element and return a copy
    $tpl = $(tpl).clone();
    // Now do your selection restricting scope to the tpl element
    $('.cart-unit-price', $tpl).text(data.price);
    // Alternative syntax
    $tpl.find('.cart-unit-price').text(data.price);
    // ... Other fields
    // When all your templating is done, append to the table
    $tpl.wrap('<tr></tr>').prependTo('table tbody');
    

    If you have the element already inserted in the table, you can use the same approach by targeting the element using a specific selector.

    If what you want is to update only the amount for that particular product you should do the following:

    $(document).ready(function() {
          var cartAdd = $('.add-to-cart')
          cartAdd.click(function(event) {
                event.preventDefault();
                // The button that was clicked
                var thisLink = $(this)
                var hrefEndpoint = thisLink.attr('data-endpoint')
                var addCartMethod = "GET"
                var linkData = thisLink.serialize();
                // Find the enclosing .cart-data element
                var cartData = thisLink.closest('.cart-data')
                // And now find the corresponding quantity container inside
                var cartQuantity = cartData.find('.cart-quantity')
    
                console.log(cartQuantity)
    
                $.ajax({
                  url: hrefEndpoint,
                  method: addCartMethod,
                  data: linkData,
                  success: function(data) {
                    // Set the new quantity
                    cartQuantity.text(data.quantity)
                    var currentPath = window.location.href
                    if (window.location.href.indexOf('cart') != -1) {
                      updateCart()
                    }
                  },
                  error: function(errorData) {
                    console.log('error')
                    console.log('error', errorData)
                  }
                })

    </div>
    
    评论

报告相同问题?