【问题标题】:how to update data in template with out refresh the page in django如何在不刷新 django 页面的情况下更新模板中的数据
【发布时间】:2020-09-29 12:42:31
【问题描述】:

我正在从事一个电子商务项目。当用户将商品添加到购物车然后将商品保存到数据库中时,我正在重新加载页面以更新模板中的购物车商品。但问题是每次页面重新加载在生产服务器中都非常关键。所以我需要有关如何更新模板中的数据而无需每次都重新加载页面的帮助。任何建议,请... 提前谢谢...

【问题讨论】:

    标签: python django-models django-rest-framework django-views django-templates


    【解决方案1】:
    # you can use ajax in your template. For example
    
    urls.py
    
    path(r'ajax/add-product/', add_product, name='search-vendor'),
    
    
    views.py
    
    from django.http import JsonResponse
    
    def add_product(request):
        data_array = []
        data = request.POST['price']
        ...
        ...
        # do you code  ...
        return JsonResponse(data_array, safe=False)
    
    
    template_name.html
    
    ...
    
    <form class="form-inline" id="addproduct-form" name="addproduct-form">
        {% csrf_token %}
        <div class="form-group">
            <input type="text" class="form-control r-0 light s-12" name="product_name">
        <input type="text" class="form-control r-0 light s-12" name="product_price">
        ...
        ...
            <input type="submit" class="btn btn-info search s-12" value="Submit">
        </div>
    </form>
    ...
    
    <table class="table table-bordered table-hover">
        <thead>
            <tr class="no-b">
                <th>Product Id</th>
                <th>Product</th>
                <th>Price</th>
                <th>Quantity</th>
            </tr>
        </thead>
        <tbody class="table-content">
        # add your content here
        </tbody>
    </table>
    ....
    ....
    <script>
    $.ajax({
        type : "POST",
        url: '/ajax/add-product/',
        data : $("#addproduct-form").serialize(),
        success: function (data) {
            $('.table-content').empty();
            $.each(data, function (key, val) {
                $(".table-content").append("\
                <tr>\
                <td>"+val['product_id']+"</td>\
                <td>"+val['product_name']+"</td>\
                <td>"+val['price']+"</td>\
                <td>"+val['quantity']+"</td>\
                </tr>\
                ");
            });
        }
    });
    
    </script>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-14
      • 1970-01-01
      • 2022-11-27
      • 2011-06-15
      • 2018-03-24
      • 2014-08-18
      • 1970-01-01
      • 2017-06-13
      相关资源
      最近更新 更多