【发布时间】:2015-07-13 05:46:12
【问题描述】:
我正在尝试在 DJango 1.7 和 Python27 中使用 Ajax 向下滚动页面时从数据库表中加载数据,它会在初始加载期间加载所有内容。请帮我解决这个问题。
Views.py:
def table_row(request, start=0, count=35): #set count here for how many ticket to load each call. Set it so it loads slightly more than enough to fill a page.
if request.method == 'POST':
filter = request.POST.get('category', False)
if filter:
tickets = Ticket.objects.filter(category=filter)
else:
tickets = Ticket.objects.all()
start = int(start)
return render_to_response('table-view.html',
{
'tickets':tickets[start:start+count], #slices the index of tickets to return
}, RequestContext(request))
table-view.html:
<script type="text/javascript">
var processing;
function loadTickets(){
//the ajax call to load more tickets into the table
var ticket_count= $('tr.ticket').length; //grabs the number of data results returned
$.ajax({
type:'post',
url:'{% url 'app.views.table_row' %}'+ticket_count+'/'+,
data:{
'csrfmiddlewaretoken':getCookie('csrftoken'), //This is the ajax csrf protection function
},
success:function(data){
$('#text-loading').toggleClass('hidden',true); //hides the loading animation when ajax call returns tickets
$('#table-body').append(data); //adds data to the end of the table
processing = false; // the processing variable prevents multiple ajax calls when scrolling
}
});
}
$(document).ready(function(){
loadTickets(); //initial ticket load
$('#main-window').scroll(function(e){
if (processing){
return false;
}
if ($('#content-window').scrollTop() >= ($('#full-table').height() -$(#'content-window').height())){
processing = true; //prevent multiple scrolls once first is hit
$('#text-loading').toggleClass('hidden', false); //show the loading animation
loadTickets();
}
});
});
在同一个文件中,我使用以下填充数据:
<td>{{ ticket.id }}</td>
<td>{{ ticket.title }}</td>
</tr>
{% endfor %}
<!--The loading animation. Appears on first page load and every time the scrolling reaches the bottom -->
<div id='text-loading'> We are loading more tickets
我怀疑 ajax 函数中的 $('tr.ticket').length 我不确定.. 它是什么.. 可能我需要找到某种方式来使用 django 约定来分配数据数量结果?请帮我解决这个问题。谢谢
【问题讨论】:
-
措辞有点混乱 - 到底有什么问题?是否有超过 35 张票正在加载(这是您的“初始”编号是多少?或者 ajax 票没有加载/附加?
-
是的,超过 35 个工单正在加载。事实上,所有可用记录最初都在加载(表中总共有 154 个)。我希望在初始加载时只有 35 张票,当我向下滚动页面时,接下来应该加载 35 张票,依此类推...
标签: javascript jquery ajax django python-2.7