Django和jQuery,实现Ajax表格数据分页展示
# views.py
from django.shortcuts import render
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
def table_data(request):
data_list = [{'id': i, 'info': f'info{i}'} for i in range(100)] # 示例数据
paginator = Paginator(data_list, 10) # 每页10条数据
page = request.GET.get('page')
try:
data = paginator.page(page)
except PageNotAnInteger:
data = paginator.page(1)
except EmptyPage:
data = paginator.page(paginator.num_pages)
return render(request, 'table.html', {'data': data})
# table.html
<!DOCTYPE html>
<html>
<head>
<title>Table Data</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#pagination-container .pagination a').click(function(e){
e.preventDefault();
var page = $(this).attr('href').split('page=')[1];
getData(page);
});
function getData(page){
$.ajax({
type: 'GET',
url: '/path/to/table-data/?page=' + page,
success: function(data){
$('#table-body').html(data['table']);
$('#pagination-container').html(data['pagination']);
}
});
}
});
</script>
</head>
<body>
<div id="table-body">
{{ data.table }}
</div>
<div id="pagination-container">
{{ data.pagination }}
</div>
</body>
</html>
这个示例展示了如何在Django后端使用Paginator来处理分页,并在前端使用jQuery和Ajax来异步加载分页后的数据。这样可以提升用户体验,不需要每次翻页都重新加载整个页面。
评论已关闭