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 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据