我正在使用这个优秀的教程为我的 Django 应用程序实现无限滚动。
我希望应用程序加载 9 篇文章,然后显示“正在加载...”标志并再加载 9 篇文章。
然而,发生的情况是,当用户点击底部时,它显示加载标志并且什么也没有发生。在终端上,我可以看到它“GET”一次请求所有页面,如下所示:
[06/Jul/2017 18:22:26] "GET /?page=2 HTTP/1.1" 200 19124 [06/Jul/2017 18:22:27] "GET /?page=3 HTTP/1.1" 200 18774 [06/Jul/2017 18:22:27] "GET /?page=4 HTTP/1.1" 200 18772 [06/Jul/2017 18:22:28] "GET /?page=5 HTTP/1.1" 200 19031 [06/Jul/2017 18:22:28] "GET /?page=6 HTTP/1.1" 200 18965 [06/Jul/2017 18:22:28] "GET /?page=7 HTTP/1.1" 200 18676 [06/Jul/2017 18:22:28] "GET /?page=8 HTTP/1.1" 200 18866 [06/Jul/2017 18:22:28] "GET /?page=9 HTTP/1.1" 200 19094 [06/Jul/2017 18:22:28] "GET /?page=10 HTTP/1.1" 200 18750
这是视图中的代码:
def context_generator(request, title, category):
"""made this function because views are very similar"""
context_dict={}
if(category == "index"):
articles_list = Article.objects.order_by('-pub_date')
else:
articles_list = Article.objects.filter(category=category).order_by('-pub_date')
page = request.GET.get('page', 1)
paginator = Paginator(articles_list, 9)
try:
articles = paginator.page(page)
except PageNotAnInteger:
articles = paginator.page(1)
except EmptyPage:
articles = paginator.page(paginator.articles_list)
context_dict['articles'] = articles
context_dict['title'] = title
return context_dict
def index(request):
return render(request, 'app_name/index.html', context_generator(request, "page title", "index"))
这是 index.html:
{% block body_block %}
<div class="container infinite-container">
{% for article in articles %}
<!-- render articles -->
{% endfor %}
</div>
{% if articles.has_next %}
<a class="infinite-more-link" href="?page={{ articles.next_page_number }}">More</a>
{% endif %}
<div class="loading" style="display: none;">
Loading...
</div>
{% endblock %}
这个脚本在 base.html 中:
<script>
var infinite = new Waypoint.Infinite({
element: $('.infinite-container')[0],
onBeforePageLoad: function () {
$('.loading').show();
},
onAfterPageLoad: function ($items) {
$('.loading').hide();
}
});
</script>
这些导入位于 base.html 标头中:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="{% static 'js/jquery.waypoints.min.js' %}"></script>
<script src="{% static 'js/infinite.min.js' %}"></script>
那是因为我忘记将这个类添加到每个文章 div 中:
infinite-item
所以它必须是这样的:
<div class="container infinite-container">
{% for article in articles %}
<div class="article col-md-4 col-lg-4 col-xs-12 infinite-item"></div>
{% endfor %}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句