Javascript 如何在发送ajax数据之前清空它?

Javascript 如何在发送ajax数据之前清空它?,javascript,ajax,Javascript,Ajax,我有一个表单,当我提交它时,它会创建一个ajax函数,然后用success中的数据创建一个表。但是知道我的页面是动态的(在不重新加载页面的情况下,我多次调用ajax函数),但是每次成功中的数据都不会在生成更多数据之前被删除。这正常吗?在发送ajax之前,如何清空success数据变量 功能: function submitForm() { if ($.fn.DataTable.isDataTable("#table")) { $('#table').Da

我有一个表单,当我提交它时,它会创建一个ajax函数,然后用success中的数据创建一个表。但是知道我的页面是动态的(在不重新加载页面的情况下,我多次调用ajax函数),但是每次成功中的数据都不会在生成更多数据之前被删除。这正常吗?在发送ajax之前,如何清空success数据变量

功能:

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>

您必须在发送前清空表

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
                }
        });
}

@Viksool的可能副本您的确切意思是什么?@Andreas您的意思是说每次调用函数(不重新加载页面)时,数据都是100%新的,并且不包含以前调用的值?如果是这样的话,为什么在下一个ajax调用中,在发送前将表destroy添加到,表中仍然有比所需更多的数据?@Dewuly,因为您正在使用
DataTable.js
,我认为这个问题与此相关,因为您无法删除旧数据,请参阅此。实际上,您所说的背后有一个想法,就是在异步ajax中删除表。但它仍然不起作用,表返回的结果比需要的多。