django jquery ajax资源被解释为Document但是使用MIME类型application / json进行传输

时间:2015-11-23 08:20:13

标签: jquery python json ajax django

我有一个html页面,显示产品列表,每个产品都有一个添加到购物车按钮。

我的html视图:

 {% for sku, name, mrp, sp, id in product_data_list %}
      <form id="add_to_cart" action="{% url 'add_to_cart' %}" method="POST">
        {% csrf_token %}
        <div class="item">
          <div class="item-inner">
            <div class="item-img">
              <div class="item-img-info"><a href="product-detail.html" title="{{name}}" class="product-image"><img src="{% static "products-images/p1.jpg" %}" alt="Retis lapen casen"></a>
                <div class="item-box-hover">
                  <div class="box-inner">
                  </div>
                </div>
              </div>
            </div>
            <div class="item-info">
              <div class="info-inner">
                <div class="item-title"><a href="product-detail.html" title="{{name}}">{{name}}</a> </div>
                  <div class="item-content">
                    <div class="rating">
                      <div class="ratings">
                        <div class="rating-box">
                          <div class="rating" style="width:80%"></div>
                        </div>
                        <p class="rating-links"><a href="#">1 Review(s)</a> <span class="separator">|</span> <a href="#">Add Review</a> </p>
                      </div>
                    </div>
                    <div class="item-price">
                      <div class="price-box"><span class="regular-price" id="product-price-1"><s><span class="price"><i class="fa fa-inr"></i>&nbsp;{{mrp}}</span></s>&nbsp;&nbsp;&nbsp;<span class="regular-price" id="product-price-1"><i class="fa fa-inr"></i>&nbsp;{{sp}}</span> </span> </div>
                    </div>
                    <div class="add_cart">
                      <button class="button btn-cart" type="submit" id="product_id" value="{{id}}"><span>Add to Cart</span></button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </form>
        {% endfor %}

上面的代码显示了数据库中的产品数据。
我正在使用ajax请求将数据发送回django视图。

我的ajax脚本:

<script>

  jQuery(document).ready(function($){$.ajaxSetup({
    beforeSend: function(xhr, settings) {
      if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
        xhr.setRequestHeader("X-CSRFToken", csrftoken);
      }
    }
  });});

  jQuery(document).ready(function($){$('#add_to_cart').on('submit', function(event){
    event.preventDefault();
    $.ajax({
        url : "/add_to_cart/", // the endpoint
        type : "POST",
        cache: false,
        async: "true",
        data : { product_id : $('#product_id').val()}, // data sent with the post request

    // handle a successful response
        success : function(json) {
            // $('#product_id').val(''); 
            console.log("success"); // another sanity check
            alert("Product Added To Cart.")
        },

     // handle a non-successful response
        error : function(xhr,errmsg,err) {
            console.log(err);
            console.log(errmsg);
            }
    });
  });});
</script>

我的django观点:

def addToCart(request):
    if request.method == 'POST':
        response_data = {}
        product_id = request.POST.get('product_id')

        try:
            try:
                cart = request.COOKIES.get('cart')
                cart = cart + '*' + product_id
                response_data['result'] = 'Added To Cart Successfully !!!'
                response = HttpResponse(json.dumps(response_data),content_type="application/json")
                response.set_cookie('cart',cart)
            except:
                cart = product_id
                response_data['result'] = 'Added To Cart Successfully !!!'
                response = HttpResponse(json.dumps(response_data),content_type="application/json")
                response.set_cookie('cart',cart)
        except:
            response_data['result'] = 'Cannot Be Added To Cart !!!'

        return response
    else:
        return HttpResponse(json.dumps({"result": "Failure !!!"}),content_type="application/json")

此代码工作正常,它将数据(product_id)添加到带有变量购物车的cookie中。 问题是,如果我的html模板呈现多个项目或产品,则ajax请求仅适用于第一个项目,而其余产品则仅添加None而不是product id。此外,它还会导航到页面localhost:8000/add_to_cart并显示字典{'result':'Added To Cart Successfully !!!'}。而对于第一个产品,它保持在同一页面而不刷新。 如何让它适用于所有项目?

编辑:在控制台中它说:

资源解释为文档但使用MIME类型application / json

传输

1 个答案:

答案 0 :(得分:0)

HTML代码中的多个元素不能与id相同,而且模板代码会以这种方式创建。使用:

<form id="add_to_cart_{{ forloop.index }}" class="add_to_cart_form" action="{% url 'add_to_cart' %}" method="POST">

代替(也修复具有相同id s的任何其他元素)并更改您的javascript代码:

  jQuery(document).ready(function($){$('add_to_cart_form').on('submit', function(event){

$(this).find('.product_id').val()