【问题标题】:How to empty ajax data before sending it?如何在发送之前清空ajax数据?
【发布时间】:2018-05-24 10:34:04
【问题描述】:

我有一个表单,当我提交它时,它会创建一个 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>

【问题讨论】:

  • @vikscool 你到底是什么意思?
  • @Andreas 所以你的意思是说每次(不重新加载页面)调用函数时,数据都是 100% 新的并且不包含先前调用的值?如果是这样,为什么当我在发送前添加我的表销毁时,在下一个 ajax 调用中,表中的数据仍然比需要的多?

标签: javascript ajax


【解决方案1】:

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

【讨论】:

  • 其实你说的背后有一个想法,就是在异步ajax中删除表。但它仍然不起作用,表返回的结果比需要的多。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-26
  • 1970-01-01
  • 2023-03-03
  • 2019-01-12
  • 2021-08-24
  • 1970-01-01
  • 2012-06-13
相关资源
最近更新 更多