javascript - 如何在发送之前清空ajax数据?
问题描述
我有一个表单,当我提交它时,它会创建一个 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>
解决方案
您必须在 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
}
});
}
推荐阅读
- mysql - 如何选择临时表并立即更新
- robotframework - 如何在 Robot Framework 中创建自定义测试用例设置,如标签
- java - Spring Security 和 GraphQL
- asp.net-mvc - Telerik MVC 网格内联编辑需要刷新页面才能显示更改
- c++ - 绑定函数中的 C++ socketio 分段错误
- python - Python-chess 打开 UCI 引擎权限错误被拒绝
- php - WooCommerce 自定义分页格式
- java - Websocket 中的 Channel vs. Broker vs. Destination
- android - 我可以去掉模型底部的白色圆圈吗?
- c# - 连接字符串错误“缺少其语句块”