首页 > 解决方案 > 如何在发送之前清空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>

标签: javascriptajax

解决方案


您必须在 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
                }
        });
}

推荐阅读