您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在Django中重新加载表数据而无需刷新页面

在Django中重新加载表数据而无需刷新页面

你可以使用setInterval,jQuery AJAX以及view

Your HTML

   <table id="_appendHere" class="table table-striped table-condensed">
      <tr>
        <th>Reg.nr.</th>
        <th>M&auml;rke</th>
        <th>Modell</th>
      </tr>
      {% for i in order %}
        {% if i.order_booked %}
        <tr class="success">
        {% else %}
        <tr>                    
        {% endif %}

         <td>{{ i.regnr|upper }}</td>
         <td>{{ i.brand|capfirst }}</td>
         <td>{{ i.brand_model|capfirst }}</td>
      </tr>
      {% endfor %}
    </table>

JS

<script>
    var append_increment = 0;
    setInterval(function() {
        $.ajax({
            type: "GET",
            url: {% url 'get_more_tables' %},  // URL to your view that serves new info
            data: {'append_increment': append_increment}
        })
        .done(function(response) {
            $('#_appendHere').append(response);
            append_increment += 10;
        });
    }, 10000)
</script>

View

def get_more_tables(request):
    increment = int(request.GET['append_increment'])
    increment_to = increment + 10
    order = Order.objects.filter(owner=request.user).order_by('-id')[increment:increment_to]
    return render(request, 'get_more_tables.html', {'order': order})

get_more_tables.html

  {% for i in order %}
  <tr>
    {% if i.order_booked %}
    <tr class="success">
    {% else %}
    <tr>                    
    {% endif %}

     <td>{{ i.regnr|upper }}</td>
     <td>{{ i.brand|capfirst }}</td>
     <td>{{ i.brand_model|capfirst }}</td>
  </tr>
  {% endfor %}

然后只需确保将新视图添加到你的视图中urls.py (确保它具有name=’get_more_tables’,或JS中的任何名称url:)

它的作用是使用setIntervalJS函数,GET每10000毫秒(10秒)向服务器中的视图发出AJAX请求。然后,该视图使用此新上下文呈现一个单独的HTML文件,并将其作为response回发送到你的原始HTML页面。response然后appended通过jQuery 将新的表添加到你的表。每次发生此循环时,切片都会递增,因此你不会从获得相同的结果Order。

请记住,这将不停地循环,因此,如果希望结束,则必须将代码添加到JS以setInterval在最后一个响应返回为空时停止。

Go 2022/1/1 18:24:49 有306人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶