【问题标题】:DataTable not refreshing when using Ajax Jquery使用 Ajax Jquery 时 DataTable 不刷新
【发布时间】:2020-05-05 22:57:15
【问题描述】:

我已经检查了与此相关的每一个问题,但似乎没有任何效果。这是我的情况:

我使用的是 1.10.20 DataTable 版本,我尝试使用 Ajax jquery($.ajax) 在服务器端插入/删除后刷新数据,然后我尝试刷新 Datatable obj,但没有成功。

我的代码:

    function displaymensajes()
{   

$.ajax({
    async: true,
    url: 'ajaxscripts.php',
    type: 'POST',
    data: ({ "WTDo" : 'displaymensajes', "userid" : <?php echo $_SESSION["IDInversionista"] ?>}) ,
    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
    success: function (response) {
    $('#tbodymensajes').html(response);



//If I make the call here($("#mensajesTable").DataTable();) instead of on document ready, the Second time the functions is called(I have to call it again when I insert or delete records) I get the error when it can't initialize twice and stuff.
//I try do the ajax.reload() no luck, its gives me the error where Json is not properly formatted(of course I not using Json format in the server side, the response is pure HTML code)
//I try delete the table and create it again, no luck

    },
    error: function () {
        alert("error");
    }
}); 

}

displaymensajes();


//On Document ready... Initialize the API
$(document).ready(function() {
 $("#mensajesTable").DataTable(); 
 } );

结果:

Table 中有 2 行,但 Datatable 仍然认为只有 1 行。只有在我刷新页面时才会赶上。帮助?。

enter image description here

PD:有人可以对此 API 进行 refresh() 或 update() 吗?

【问题讨论】:

  • 问题是您要替换 tbody 而不是整个表 - 您可以返回整个表(如果您不想使用 .destroy)
  • 我可以试试看效果如何
  • 是的!!!!是的!!!!!!....天啊...它有效,谢谢!!!.. 不在一百万年后我会考虑这个!感谢您的帮助!!!

标签: jquery datatable


【解决方案1】:

在进行 ajax 调用后,您需要使用 ajax 调用的响应将表格的 HTML 替换为更新后的 HTML。 如果不查看更多代码,很难说您将如何执行此操作,但一种常见的方法是将服务器端代码中的表格内容作为 HTML 返回并替换更新的内容。为此,您需要在 ajax 调用中添加如下内容:

$.ajax(...<your current code>).done(function(response){
    $("#yourTableId").html(response)
});

为此,您的服务器端代码需要返回更新的 HTML(或 JSP 或您正在使用的任何内容)作为对 ajax 调用的响应。

【讨论】:

  • 所以我应该使用 .done 来代替成功:函数(响应)
  • .done / success: 在这里做同样的事情 - 如果你内联包含它,你可以使用任何一个
  • 好的,我曾经这样做过:$.ajax(..my code..).done(function(response){$('#tbodymensajes').html(response); $("#mensajesTable").DataTable();}); 并且 Jquery 内部工作得很好,但数据表仍然没有刷新......在我使用另一个 ajax 函数成功插入记录后我调用displaymensajes(),我在表中的行数超过了数据表列出的行数
  • 有趣的是,在我使用 Done 而不是 Success 之后,我没有从数据表中得到“无法初始化两次”错误。还是不行,但是进步就是进步lol
  • 你能添加你的服务器端代码吗?您要确保它发送的响应在更新后具有数据。接收到 ajax 调用时触发的服务器端代码应该更新数据库,从数据库中提取新值,然后返回生成的 HTML 以及更新的数据作为响应。
猜你喜欢
  • 1970-01-01
  • 2016-10-13
  • 1970-01-01
  • 2020-02-06
  • 2016-01-09
  • 2013-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多