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

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (57)

我在用Django的内置pagination若要将数据分页并在模板中显示,请执行以下操作。现在,我希望实现jQuery,使用Ajax将页面加载并附加到模板中。我如何使用jQuery来完成它呢?

我在用Django-无穷无尽的分页以前,但是由于它通过JavaScript添加了条目,Mylightbox就不会捕获图像元素,而只显示在第一次请求时加载的条目。

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
        })

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 %}

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 %}
提问于
用户回答回答于

我还会用Django-无穷无尽的分页(这是目前最好的基于Ajax的分页插件),解决问题的方法将是将lightbox在分页请求完成后,请阅读更多信息。

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

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

我会给你看一个示例应用程序。因为你只是在学习,如果你真的用下面的代码制作一个这样的应用程序,这将是有帮助的。

我已经试着尽可能少地保留代码。

模型S.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>

扫码关注云+社区