Django的开发文档有一个自带的Paginator分页器,可以很方便的在原生的模板中进行调用函数分页;
但是异步请求不能给模板传入对象,该怎么分页了?
1、就将分页需要用到的数据从对象中提前取出来,放在字典里面
2、前台调用时候不再从对象中取,而是字典中取,完成分页样式;
#views.py
获取返回列表res
从请求中获取分页面数目per_page
从请求中获取当前页面current_page#对原始结果集进行分页的处理函数
def paginator(res, per_page, current_page):p = Paginator(res, per_page)contacts = p.page(current_page)return {"current_num": contacts.number,"total_nums": contacts.paginator.num_pages,'has_next': contacts.has_next(),'has_prev': contacts.has_previous(),'next_page': contacts.next_page_number() if contacts.has_next() else 0,'prev_page': contacts.previous_page_number() if contacts.has_previous() else 0,'objects': contacts.object_list,}
//异步请求的地方,将收到的json数据,显示成分页样式
function get_pools(current_page) {$.ajax({url: "/pool/info/pools",type: "GET",data: {"server_ip": get_cur_server(),"per_page":2,"current_page":current_page},datatype: 'json',success: function (contacts) {var arg=paginator(contacts);}});
}//.step-links是html已经存在的div;对里面加上前一页,当前页,总页数,后一页
function paginator(contacts) {$(".step-links").empty();if(contacts.has_prev){$(".step-links").append('<span><a page_num="'+contacts.prev_page+'"><</a></span>');}$(".step-links").append('<span class="current" page_num="'+contacts.current_num+'"> Page '+contacts.current_num+' of Total '+contacts.total_nums+'.</span>');if(contacts.has_next){$(".step-links").append('<span><a page_num="'+contacts.next_page+'">></a><span>');}return contacts.objects;
}
#可以同时显示5个页的示例var total = contacts.total_nums;var current = contacts.current_num;var start=0,end= 4;var middle;if(current<=3){middle = start+current-1;}else if(current>=total-1){middle = end - (total - current);}else {middle = (start+end)/2;}for(var i=0;i<5;i++){var page = current-middle+i;if(1<=page && page<=page_length){if(page == current){$(".step-links").append('<a class="current" page_num="'+page+'">'+page+'</a>');}else {$(".step-links").append('<a page_num="'+page+'">'+page+'</a>');}}}$(".step-links").append(' of Total '+total+'. </span>');