当前位置: 动力学知识库 > 问答 > 编程问答 >

AJAX Pagination - small problem getting Next and Previous links to work (using jQuery and Django)

问题描述:

I have a search box on a page that needs to update it's results without refreshing the entire page. I'm using Django views to serve up the results, and am using jQuery to fetch and load the results on page. My problem is similar to this Stack O. question but I can't figure out how to properly generate the Next and Previous links.

Here is the Django search view:

def search_page(request):

# Perform the search and return a QuerySet

form = SearchForm()

contentq = []

show_results = False

if 'query' in request.GET:

show_results = True

query = request.GET['query'].strip()

if query:

form = SearchForm({'query' : query})

contentq = ContentQueue.objects.filter(

description__icontains=query

)

query = query.replace(' ', '+')

# This next section sets up Paginator

ITEMS_PER_PAGE = 6

paginator = Paginator(contentq, ITEMS_PER_PAGE)

try:

page_number = int(request.GET['page'])

except (KeyError, ValueError):

page_number = 1

try:

page = paginator.page(page_number)

except InvalidPage:

raise Http404

contentq = page.object_list

variables = RequestContext(request, {

'form': form,

'contentq': contentq,

'show_results': show_results,

'query': query,

'show_paginator': paginator.num_pages > 1,

'has_prev': page.has_previous(),

'has_next': page.has_next(),

'page': page_number,

'pages': paginator.num_pages,

'next_page': page_number + 1,

'prev_page': page_number -1

})

if request.GET.has_key('ajax'):

return render_to_response('contentq.html', variables)

else:

return render_to_response('create_collection_ui.html', variables)

Here is the jQuery script that calls the Django search view:

 function search_submit() {

var query = $("#id_query").val();

$("#search-results").load("/search/?ajax&query=" + encodeURIComponent(query));

return false;

}

$(document).ready(function () {

$("#search-form").submit(search_submit);

});

And lastly, here is the HTML that is forming the Next and Previous links.

{% if show_paginator %}

{% if query %}

<div class="paginator">

{% if has_prev %}

<a href="?page={{ prev_page }}&query={{ query }}">&laquo; Previous</a>

{% endif %}

{% if has_next %}

<a href="?page={{ next_page }}&query={{ query }}">Next &raquo;</a>

{% endif %}

(Page {{ page }} of {{ pages }})

</div>

{% else %}

<div class="paginator">

{% if has_prev %}

<a href="?page={{ prev_page }}">&laquo; Previous</a>

{% endif %}

{% if has_next %}

<a href="?page={{ next_page }}">Next &raquo;</a>

{% endif %}

(Page {{ page }} of {{ pages }})

</div>

{% endif %}

{% endif %}

Feel so close, yet so far away! Any help would be greatly appreciated.

网友答案:

Spent some more time understanding the solution I referenced in my question and was able to figure this out. I pretty much used the solution code as is, except for changing the tags of course.

分享给朋友:
您可能感兴趣的文章:
随机阅读: