jQuery DataTables重复项最初加载

时间:2016-05-27 16:36:48

标签: javascript jquery ajax datatables reload

所以,从昨天开始添加我的问题:jQuery AJAX call function on timeout

使用昨天发布的第一个答案,该表确实在不刷新整个页面的情况下重新加载。它会在30秒后完成。

但我的问题出在第一次刷新之前......

页面加载,记录重复。但是在第一次刷新和每次刷新之后(除非我使用F5手动刷新),一切都很好。没有重复。

我正在试图弄清楚为什么会有重复项以及如何在页面的初始就绪事件中删除重复项。

以下是代码,从ready事件开始:

 $(document).ready(function()
 {
   $.ajax({
     url:'api/qnams_all.php',
     type:"GET",
     dataType:"json"
   }).done(function(response) {
     console.log(response.data);
     renderDataTable(response.data)
   }).fail(function() {
     alert( "error" ); 
   }).always(function() {
     alert( "complete" );
   });
 });

以下是加载DataTable的功能:

 function renderDataTable(data)
 {
   var $dataTable = $('#example1').DataTable({
     "ajax": 'api/qnams_all.php',  // just added this
     "data": data,
     "bDestroy": true,
     "stateSave": true
   });

 // then I add the reload function

   setInterval( function () {
     $dataTable.ajax.reload();
   }, 30000 );

 });

如上所述,setInterval函数的工作原理与它的应用方式相同。这只是初始页面加载重复所有记录。

有谁知道为什么以及如何解决它?

2 个答案:

答案 0 :(得分:1)

我认为你有一些重复。您不需要加载ajax flie,然后在设置DataTable时再次加载它。

尝试用以下代码替换所有代码:

$(document).ready(function() {
  // load and render the data
  var $dataTable = $('#example1').DataTable({
    "ajax": 'api/qnams_all.php', // just added this
    "data": data,
    "bDestroy": true,
    "stateSave": true,
    // the init function is called when the data table has finished loading/drawing
    "init": function() {
      // now that the initial data has loaded we can start the timer to do the refresh
      setInterval(function() {
        $dataTable.ajax.reload();
      }, 30000);

    }
  });
});

答案 1 :(得分:0)

在将数据加载到表中时,调用clear可防止重复行:

$("#checkResourcesButton").click(function() {
        $.post("./get/resources", {
            featureName: $('#myvar').val()
        }).done(function (data) {
            var table = $('#table-output').DataTable();
            table.clear();
            var json = JSON.parse(data);

            for (var row in json) {
                var nameVal = json[row].Name;
                var emailVal = json[row].emailId;
                var roleVal = json[row].role;
                var startDateVal = json[row].startDate;
                var endDateVal = json[row].endDate;
                var toAdd =
                    {
                        name: String(nameVal),
                        emailId: String(emailVal),
                        role: String(roleVal),
                        startDate: String(startDateVal),
                        endDate: String(endDateVal)
                    };
                table.row.add(toAdd);
            }

            table.draw();
        });
    });
相关问题