我在服务器端使用django,当用户单击单选按钮时,我需要使用新产品刷新数据表。我已经在页面加载时初始化数据表,并在等待用户单击单选按钮。单击按钮后,我向views.py
进行了ajax调用,以发送表模板的render_to_string
并返回JSONResponse
。
整个ajax都可以正常工作,除了,我无法重新初始化数据表。我尝试过:
.clear().destroy()
并重新初始化表格empty()
tbody
div,然后重复#1 .clear().draw()
而不是销毁这些都不起作用。这就是我所拥有的:
views.py
def get_products(request):
data = {}
cat_name = request.GET.get('cat_name')
brand_name = request.GET.get('brand_name')
list_of_prods = Product.objects.filter(category__name=cat_name).filter(brandname=brand_name)
data['html_products_table'] = render_to_string('templates/products/partials/products_table.html', {'list_of_prods': list_of_prods})
return (JsonResponse(data))
partials/products_table.html
{% for product in list_of_prods %}
<tr>
<td><button class="btn btn-primary btn-circle" type="button"><i class="fa fa-plus"></i></button></td>
<td>{{product.stock}}</td>
<td>{{product.code}}<br><small>{{product.description}}</small></td>
<td>{{product.price}} <br><small>{{product.manufacturer}}</small></td>
</tr>
{% endfor %}
products_home.html
<div class="table-responsive">
<table class="table table-striped table-bordered table-hover" id="products_table" cellspacing="0" width="100%">
<thead style="display: none">
<tr>
<th>Add Button</th>
<th>Stock count</th>
<th>Description</th>
<th>Price</th>
</tr>
</thead>
<tbody class="products_table_body">
{% comment %} {% include 'templates/products/partials/products_table.html' %} {% endcomment %}
</tbody>
</table>
</div>
<script>
$("input[name='brand_name']").change(function(){
$.ajax({
url: "{% url 'get_products' %}",
type: 'get',
dataType: 'json',
data:{
brand_name: brand_name,
cat_name: cat_name
},
beforeSend: function(){
console.log("Sending Data from line 156");
},
success: function(data)
{
$("#products_table").DataTable().clear().destroy();
$("#products_table").dataTable({
searching: false,
"bLengthChange": false,
});
$(".products_table_body").empty();
$("#products_table").html(data.html_products_table);
});
</script>
这最终要做的是生成一个没有分页,没有DT css样式并且没有项目计数的巨型列表<tbody>
html。