我正在尝试使用以下代码进行 ajax 分页:
// AJAX pagination
$(".pages .prev").live('click', function(event) {
event.preventDefault()
var current_page = parseInt(getParameterByName('page'))-1;
$.get('/ajax/financial_page/', {'page': current_page}, function(response) {
$(".content table").replaceWith(response)
});
})
在我看来函数:
def financial_page(request):
"""
Returns a single financials page, without extra HTML (used in AJAX calls).
"""
page = int(request.GET.get('page', 1))
if request.user.is_superuser:
fs = FinancialStatements.objects.order_by('-date', 'statement_id')
else:
up = request.user.get_profile()
providers = up.provider.all()
fs = FinancialStatements.objects.filter(provider__in=providers).order_by('-date', 'statement_id')
fs_objects, current_page_object, page_range = paginator(request, objects=fs, page=page, number_per_page=30)
data = { 'fs':fs_objects,
'page_range': page_range,
'current_page': current_page_object,
}
page = render_to_string('financial_section.html', data, RequestContext(request))
return HttpResponse(simplejson.dumps([page]))
但是,我遇到了两个问题。首先是 response
并不是真正的 HTML,而是一堆 n\t\t\n\t\t\n\t\n\t\n\t\n\t\t\n\t\
等。此外,我无法跟踪当前页面/根据需要更改 url。我将如何在这里构建一个功能性的 ajax 分页?
更新:我通过执行 response = $.parseJSON(response);
找到了第一个。我如何跟踪我在哪个页面?
最佳答案
要跟踪页面,您可以使用 AJAX 函数在单击时递增/递减变量。试试这个:
var counter="0";
$(document.body).on('click', ".pages .prev, .pages .next", function(event) {
if($(this).hasClass('prev')
counter--;// <--decrement for clicking previous button
else if($(this).hasClass('next')
counter++; // <--increment for clicking next button
event.preventDefault()
$.get('/ajax/financial_page/', {'page': counter}, function(response) {
$(".content table").replaceWith(response)
});
})
我也不会使用 live
方法,因为它在 jQuery 1.7 中已被弃用。它已被 on
方法取代。请在此处查看 jQuery on()
API:http://api.jquery.com/on/
关于javascript - 创建ajax分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10475235/