【问题标题】:How to update/refresh datatable after an ajax update or insert call?如何在 ajax 更新或插入调用后更新/刷新数据表?
【发布时间】:2018-04-14 07:12:52
【问题描述】:

我在这里有这张表,它由我的数据库中的查询结果填充:

<div class="card-block">
    <table id="catTbl" class="display" width="100%" cellspacing="0"  data-toggle="modal" data-target="#cat-update">
         <thead>
             <tr>
                 <th>ID</th>
                 <th>Title</th>
             </tr>
         </thead>
         <tbody>
             <?php
                 include "../processes/getLists.php";
                 $process = new getLists();
                 $process->getCatForTbl();
                 //used PHP PDO for that
             ?>
         </tbody>
      </table>
      <p id="message" style="margin-top: 15px"></p>
</div>

我可以使用 ajax 在数据库中正确更新和插入行,因此页面不会在每次处理后加载,但问题是如果我在每次插入/更新后不重新加载页面,数据表将不会更新新更新/插入的行。

我尝试了$("#catTbl").ajax.reload()$("#catTbl").clear().draw(),但除非我的表以某种方式由json 组成,否则它们将无法工作。每次ajax调用后我可以做些什么让我的表重新加载? 补充:我不想重新加载整个页面,只需要提交事件时的数据表。

$('#updateCatForm').on("submit", function(event){
    event.preventDefault();
    $.ajax({
        url:"../ajax/updateCat.php",
        method:"POST",
        data:$('#updateCatForm').serialize(),
        success:function(data){
            $('#updateCatForm')[0].reset();
            $('#cat-update').modal('hide');
            $('#message').html(data);
            //I put the table reload solutions here and nothing seemed to work :<
        }
    })
});

【问题讨论】:

  • document.location.reload() 在回调中?
  • 谢谢,我刚用过它,它可以工作,但它会刷新页面,但我只想刷新表格而不是整个页面。

标签: javascript php jquery ajax datatables


【解决方案1】:

使用这个

$('#example').DataTable().ajax.reload();

确保选择器相同。或者你可以简单地存储在一个变量中并像这样使用它

var table = $('#example').DataTable();

然后在ajax之后

table.ajax.reload();

---编辑----

table.ajax.reload({
    "ajax": {
           "url": '${ctx}/work/list_ajax.json',
           "type": 'POST',
           "data":{ 
              data:$('form').serialize()
           }
    } 
});

我对此并不完全确定,我没有尝试过,但它是沿着这条线获取数据并显示在表格上的。很抱歉,我无法为您提供有效的 sn-p。请记住,返回的数据应采用正确的格式,否则将无法正常工作。

【讨论】:

  • 不工作,如上所述我已经尝试过table.ajax.reload()。它给了我一个警告:DataTables 警告:table id=catTbl - Invalid JSON response。
  • 所以,刷新 url 应该返回一些 json 响应。
  • 对不起,我没有跟进此事。有点忙。所以在这里你手动获取表的数据。相反,请尝试使用 dataTable ajax 来获取您想要的数据。这样你甚至不必手动调用 reload,它应该为你调用它。
猜你喜欢
  • 2013-09-22
  • 2012-04-27
  • 2011-03-11
  • 1970-01-01
  • 1970-01-01
  • 2020-05-07
  • 1970-01-01
  • 2018-02-24
  • 1970-01-01
相关资源
最近更新 更多