weixin_33694620 2017-07-01 08:40 采纳率: 0%
浏览 41

使用Ajax更新表

I have a data table that I am trying to append rows to when there is new data to display. I'm relatively inexperienced so I took the easy way out on this and wanted to write a script that checked the database for updates every second instead of listening for server-sent events. I tried to write an Ajax query that would get all the objects in the data table, and if their 6th value is false (which means they have not been loaded), then it would add a row to my data table with that information. My tables are in a Django webapp, and here's the code I have tried to implement:

<script type="text/javascript">
      $(document).ready(function(){
          var table = $('#example').DataTable();
          setInterval(function(){
            newrequests = $.ajax({
                type: "GET",
                url: "/main/newrequests/",

                // I tried this and it didn't work

                // success: function(data) {
                //     for(i = 0; i < data.length; i++){
                //       // check if the request has been loaded
                //       if(data[i][5] == 0)
                //         // if not, load and set to loaded
                //         table.row.add(data[i]).draw;
                //         data[i][5] == 1;
                //     }
                // }
            });

            for(i=0; i<newrequests.length; i++){
              if (newrequests[i][5] == 0){
                table.row.add(newrequests[i]).draw();
                newrequests[i][5] = 1;
              }
            }

          }, 1000)
      });
</script>

I have a view set up for /main/newrequests which simply all the objects in the database:

def newrequests(request):
    return HttpResponse(Request.objects.all())

When I update the database, the data table does not refresh. Does anyone know what I am doing wrong? I feel like it might be how I am trying to use Ajax.

  • 写回答

1条回答 默认 最新

  • weixin_33704234 2017-07-01 08:58
    关注

    Datatable already has an option for that:

    var table = $('#example').DataTable({
        "ajax": '/main/newrequests'
    });
    
    setInterval(function () {
        table.ajax.reload();
    }, 30000 );
    

    https://datatables.net/examples/data_sources/ajax.html https://datatables.net/reference/api/ajax.reload()

    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c