我有一个表单,当我提交它时会创建一个ajax函数,然后在成功中从数据中创建一个表。但是知道我的页面是动态的(没有重新加载页面我多次调用ajax函数),但每次成功中的数据在生成更多数据之前都不会被删除。这是正常的吗?如何在发送ajax之前清空成功数据变量?
功能:
function submitForm() {
if ($.fn.DataTable.isDataTable("#table")) {
$('#table').DataTable().clear();
$('#table').DataTable().destroy();
$('#table').empty();
}
url = $("#form").serialize();
console.log(url);
$(document).ready(function() {
$.ajax({
type: "GET",
dataType: "json",
url: '/api/test?'+url,
'beforeSend': function (request) {
data = {}; // like this maybe?
},
success: function (data) {
//Getting data variable containing
data = data.data;
//the second time I call the function, data contains the new and old stuff at the same time
}
});
}
表格:
<form method="GET" action="" class="form-horizontal" id="form" onsubmit="return false;">
<button type="submit" onclick="submitForm();">Update table</button>
</form>
表:
<table class="table table-striped display nowrap col-md-12" id="achats_table">
<thead>
<tr style="border-bottom:2px dashed #ccc"></tr>
</thead>
<tbody></tbody>
<tfoot align="right">
<tr></tr>
</tfoot>
</table>
答案 0 :(得分:0)
您必须在beforeSend中清空表格,
function submitForm() {
url = $("#form").serialize();
console.log(url);
$(document).ready(function() {
$.ajax({
type: "GET",
dataType: "json",
url: '/api/test?'+url,
'beforeSend': function (request) {
if ($.fn.DataTable.isDataTable("#achats_table")) {
$('#table').DataTable().clear();
$('#table').DataTable().destroy();
$('#table').empty();
}
},
success: function (data) {
//Getting data variable containing
data = data.data;
//the second time I call the function, data contains the new and old stuff at the same time
}
});
}