如何使用jQuery和Django分页追加数据页面?

时间:2015-06-18 14:55:35

标签: jquery ajax django pagination

我正在使用Django的内置pagination来分页数据并在模板中显示。我现在想要实现jQuery来使用ajax加载页面并将其附加到模板。我如何使用jQuery做到这一点?

之前我使用的是django-endless-pagination,但由于它通过JavaScript添加条目,我的灯箱显示图像不会捕获图像元素,只会显示第一次请求时加载的条目。

views.py:

def snaps(request):
    snapgroup_list = SnapGroup.objects.all()
    paginator = Paginator(snapgroup_list, 1)

    try:
        page = int(request.GET.get('page', '1'))
    except:
        page = 1
    try:
        snapgroup = paginator.page(page)
    except(EmptyPage, InvalidPage):
        snapgroup = paginator.page(page)

    index = snapgroup.number - 1  # edited to something easier without index
    max_index = len(paginator.page_range)
    start_index = index - 3 if index >= 3 else 0
    end_index = index + 3 if index <= max_index - 3 else max_index
    page_range = paginator.page_range[start_index:end_index]

    return render(request, 'snaps.html', {
        'page_range': page_range,
        'snapgroup':snapgroup
        })

snaps.html:

{% extends "base.html" %}
{% block main_content %}

<div id="main_content">
    <div id="snap_wrapper" class="container">
        <hr>
        {% if snapgroup.object_list.count > 0 %} 
            {% include 'snapgroups.html' %}
        {% else %}
            <li><p>No SNAPS yet!</p></li>
            <span class="clear_both"></span>
        {% endif %}
    </div>

</div>
<div class="container">
    <div class="prev_next">
        {% if snapgroup.has_previous %}
          <a class="prev btn btn-info" href="?page={{snapgroup.previous_page_number}}">Prev</a>
        {% endif %}
        {% if snapgroup.has_next %}
          <a class="next btn btn-info" href="?page={{snapgroup.next_page_number}}">Next</a>
        {% endif %}
        <div class="pages">
          <ul>
          {% for pg in page_range %}
            {% if snapgroup.number == pg %}
              <li><a href="?page={{pg}}" class="btn btn-default">{{pg}}</a></li>
            {% else %}
              <li><a href="?page={{pg}}" class="btn">{{pg}}</a></li>
            {% endif %}
          {% endfor %}
          </ul>
        </div>
        <span class="clear_both"></span>
    </div>  
</div>

{% endblock %}

snapgroups.html:

{% for sg in snapgroup.object_list %}
    <h4 id="combination" class="snap_date">{{sg.date|date:'l'}}, {{sg.date}}</h4>
    <ul>
    {% for snap in sg.snap_set.all %}
        <li><a href="{{MEDIA_URL}}{{snap.image}}" data-imagelightbox="f"><img src="{{MEDIA_URL}}{{snap.image}}" alt="{{snap.caption}}" /></a></li>
    {% endfor %}
        <span class="clear_both"></span>
    </ul>
{% endfor %}

2 个答案:

答案 0 :(得分:6)

我向您展示了一个示例应用。由于您只是在学习,如果您使用下面的代码实际制作一个这样的应用程序,这将会很有帮助。

我尽可能地将代码保持在最低限度。

models.py

class Article(...):
    title = models.CharField(...)
    photo = models.ImageField(...)

views.py

import json

def article_ajax(request):
    TOTAL = 10
    OFFSET = request.GET.get('offset', 0)
    END = offset + TOTAL
    # TOTAL means how many articles to load
    # in a single request

    # to understand OFFSET and END, consider this:
    # mylist = [1,2,3,4,5,6,7,8,9]
    # mylist[2:5] outputs => [3,4,5]
    # Above 2 is OFFSET and 5 is END

    articles = Article.objects.all()[OFFSET:END]

    json_list = []
    for article in articles:
        json_list.append({
            'title': article.title, 'photo_url': article.photo.url
        })

    data = json.dumps(json_list)

    return HttpResponse(data, content_type='application/json')

urls.py

...
url(r'^ajax/articles/$', 'myapp.views.article_ajax'),
...

articles.html

该脚本也包含无限滚动代码:)

<!-- All articles will be loaded in following div -->
<div id="ArticlesDiv"></div>

<script>
var articleOffset = 0;

var articleLoader = function() {
    $.ajax({
        url: '/ajax/articles/?offset=' + articleOffset,
        success: function(data) {
            if (data.length > 0) {
                for (var i = 0, total = data.length; i < total; i++) {
                    var compile_data;
                    compile_data = '<h1>' + data[i].title + '</h1>\
                        <img src="' + data[i]photo_url + '">';

                    $('#ArticlesDiv').append(compile_data);
                }

                /* update the offset */
                articleOffset += 10
            } else {
                $('#ArticlesDiv').append('No articles found');
            }
        }
    });
}

/* Infinite scrolling for fetching articles */
var $window = $(window);
function prodScrollPosition() {
    var distance = $window.scrollTop() + $window.height();
    if ($('body').height() <= distance && $('#ArticlesDiv')) {
        articleLoader();
    }
}

$window.scroll(prodScrollPosition).scroll();

/* Manually initiate the first ajax request */
articleLoader();
</script>

答案 1 :(得分:3)

我仍然会使用django-endless-pagination(它是最好的基于ajax的分页插件),问题的解决方案是在分页请求完成后调用lightbox init,详细了解callbacks

<script type="text/javascript">
    function hookup_lightbox(){
        $( selector ).imageLightbox();
    }

    $.endlessPaginate({
        onCompleted: function(context, fragment) {
            // hookup lightbox
            hookup_lightbox();
        }
    });
</script>