我在Django项目中使用的是DataTables 1.10.20版。
我在页面中有两个数据表,一个用于产品,另一个用于购物车。
“产品”表中的数据通过AJAX调用获得。用户将通过单击添加按钮将产品从产品表添加到购物车表。用户应该能够修改购物车表中的数量,并在满意后最终单击结帐按钮。结帐按钮将调用某些视图以保存保存交易的后续步骤。
问题是,在单击结帐之前,如果用户在添加几个产品后刷新页面或导航到另一个页面,则购物车数据表会丢失所有数据,并且用户会必须重新添加它们。
购物车数据表中的数据仅应在单击“结帐”时清除。这可能吗?
我尝试使用here中记载的StateSave: true
,但没有帮助。
这是我的代码。
“产品”的数据表
<script defer type="text/javascript" language="javascript" class="init">
// This function will initialilize the 'Products' datatable.
$(document).ready(function () {
$('#productstable').dataTable({
"ajax": {
"url": "{% url 'getproductsdata' %}",
"dataSrc": ''
},
// Datatable customization options
// Hide default datatable out of the box search feild
"dom": 'lrtip',
// Disable paging i.e nubering , next page etc ...
//"paging": false,
"pageLength": 2,
// Disable total results found info
//"info": false,
"rowId": 'pk',
"columns": [
// Hiding the Primary Key in Datatable View
{ "data": "pk", "visible": false },
{ "data": "fields.product_id" },
{ "data": "fields.product_name" },
{ "data": "fields.size" },
{ "data": "fields.units_per_case", "visible": false },
{
mRender: function (data, type, row) {
return '<button type="button" id="addtowscart" class="bg-gradient-success">Add</button>'
}
}
]
});
// IMPORTANT :- Hide the table data initially
$('#productstable').hide();
});
</script>
“购物车”和“添加到购物车”功能的数据表
<script>
// Cart Table
$(document).ready(function () {
// Get Products and Cart datatable's instances..
var products_table = $('#productstable').DataTable();
var wscart_table = $('#wscarttable').DataTable({
// Datatable customization options
// Hide default datatable out of the box search feild
"dom": 'lrtip',
// Disable paging i.e nubering , next page etc ...
"paging": false,
// Disable total results found info
"info": false,
StateSave: true,
columns: [{data: 'idnum'}, {data: 'productid'},
{
mRender: function (data, type, row) {
return '<input type="number" value="1" id="qty-btn" min="0" max="100" step="1"/>'
}}
],
});
// Add to Cart
$('#productstable tbody').on('click', '#addtowscart', function (e) {
e.preventDefault();
var table = $('#productstable').DataTable();
var idx = table.row($(this).parents('tr')).data();
wscart_table.row.add( {
"idnum": idx.pk,
"productid": idx.fields.product_id,
} ).draw();
});
});
</script>