最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Creating ajax pagination - Stack Overflow

programmeradmin0浏览0评论

I am trying to do an ajax pagination with the following code:

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

And in my view function:

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

However, there are two problems I'm running into. The first is that the response is not really HTML, and has a bunch of n\t\t\n\t\t\n\t\n\t\n\t\n\t\t\n\t\, etc. Also, I'm having trouble keeping track of the current page/changing the url as needed. How would I build a functional ajax pagination here?

Update: I figured out the first one, by doing response = $.parseJSON(response);. How would I keep track of which page I am on though?

I am trying to do an ajax pagination with the following code:

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

And in my view function:

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

However, there are two problems I'm running into. The first is that the response is not really HTML, and has a bunch of n\t\t\n\t\t\n\t\n\t\n\t\n\t\t\n\t\, etc. Also, I'm having trouble keeping track of the current page/changing the url as needed. How would I build a functional ajax pagination here?

Update: I figured out the first one, by doing response = $.parseJSON(response);. How would I keep track of which page I am on though?

Share Improve this question edited May 6, 2012 at 23:50 David542 asked May 6, 2012 at 23:42 David542David542 111k206 gold badges568 silver badges1k bronze badges 2
  • -@David542 wouldn't just decrementing/incrementing a variable onclick keep track of the page for you? – tim peterson Commented May 7, 2012 at 2:14
  • is your question answered yet? – tim peterson Commented May 9, 2012 at 11:37
Add a ment  | 

4 Answers 4

Reset to default 2

To keep track of the page, you can increment/decrement a variable on click with your AJAX function. Try this:

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

I would also not use live method as it is deprecated as of jQuery 1.7. It has been replace by the on method. See the jQuery on() API here: http://api.jquery./on/

Check this tutorial about "Ajax Scroll Paging Using jQuery, PHP and MySQL", it may simplify your job: http://www.bewebdeveloper./tutorial-about-ajax-scroll-paging-using-jquery-php-and-mysql

Here is the essential from:

var is_loading = false; // initialize is_loading by false to accept new loading
var limit = 4; // limit items per page
$(function() {
    $(window).scroll(function() {
        if($(window).scrollTop() + $(window).height() == $(document).height()) {
            if (is_loading == false) { // stop loading many times for the same page
                // set is_loading to true to refuse new loading
                is_loading = true;
                // display the waiting loader
                $('#loader').show();
                // execute an ajax query to load more statments
                $.ajax({
                    url: 'load_more.php',
                    type: 'POST',
                    data: {last_id:last_id, limit:limit},
                    success:function(data){
                        // now we have the response, so hide the loader
                        $('#loader').hide();
                        // append: add the new statments to the existing data
                        $('#items').append(data);
                        // set is_loading to false to accept new loading
                        is_loading = false;
                    }
                });
            }
       }
    });
});

Try using the javascript String.replace() method:

// AJAX pagination
$(".pages .prev").live('click', function(event) {
    event.preventDefault()
    var current_page = parseInt(getParameterByName('page'))-1;
    $.post('/ajax/financial_page/', {'page': current_page}, function(response) {
        response = response.replace(/\n/g,'<br>').replace(/\t/,'&nbsp;&nbsp;');
        $(".content table").replaceWith(response)
    });
})
jQuery.get(url, [data], [callback], [type])

type :xml, html, script, json, text, _default。

how about trying to define the last parameter as "html" ?

发布评论

评论列表(0)

  1. 暂无评论