Django - Ajax分页

目前总结了2种方法:

1. Ajax 分页

尼玛各种google,stackoverflow,搞了好久才总结出这个,之前使用Pagination tag loading的方式不好用,并且不能进行ajax提交请求的页面无刷新的方式去分页

1.view.py

 1 from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
 2 from django.shortcuts import render
 3 def xxx(request):
 4             rows = cursor.fetchall()
 5             paginator = Paginator(rows, 15) //how many items per page
 6             page = request.POST.get('page')
 7             try:
 8                 rows = paginator.page(page)
 9             except PageNotAnInteger:
10                 # If page is not an integer, deliver first page.
11                 rows = paginator.page(1)
12             except EmptyPage:
13                 # If page is out of range (e.g. 9999), deliver last page of results.
14                 rows = paginator.page(paginator.num_pages)
15     return render(request,'ajax_page.html', {'rows': rows})

2. ajax_page.html

<div class="pagination">
    <span class="step-links">
        {% if rows.has_previous %}
            <a id='pre' href="#">previous</a>
        {% endif %}
        <span class="current">
            Page {{ rows.number }} of {{ rows.paginator.num_pages }}.
        </span>
        {% if rows.has_next %}
            <a id="next" href="#" >next</a>
        {% endif %}
    </span>
</div>

3. JS -Ajax 部分

 1 {%block js%}
 2   <script type="text/javascript">
 3      $('.step-links #next').click(function(){
 4         {% if rows.has_next %}
 5         page={{ rows.next_page_number }};
 6              {% endif %}
 7         $.ajax({type:"POST",url:"/submitjobs/",data:{"page":page},10         success:function(data){
11             $("#jobs_table").html(data);    
12                     }
13             })
15      });    
16      $('.step-links #pre').click(function(){
17          {% if rows.has_previous %}
18         page={{ rows.previous_page_number }};
19       {% endif %}
20         $.ajax({type:"POST",url:"/submitjobs/",data:{page":page},23         success:function(data){
24             $("#jobs_table").html(data);    
25                     }
26             })
27      });
28  </script>
29   {%endblock%}

 

2. Datatable - plugin for Jquery (http://datatables.net/)

这种方法quick and dirty 唯一缺点就是不适用海量数据一般几百来页也是可以的,只需在js中调用dataTable方法就好。

数据填充已经在方法1中使用render.request将数据载入table.

{%block js%}
<script type="text/javascript">
$('#job_table').dataTable();
</script>
{%endblock%}

 

posted @ 2016-02-20 17:46  西番莲果汁  阅读(2727)  评论(1编辑  收藏  举报