简体   繁体   中英

Prevent multiple Ajax request (pagination with pushstate)

There I had a problem with ajax pagination with HTML API Pushstate.

So, this is my code:

<ul class="small">
    <li>
        <p>a</p>
    </li>
</ul>

<ul class="paging">
    <li><a href=/page2>2</a></li>
    <li><a href=/page3>3</a><li>
    <li><a href=/page4>4</a><li>
</ul>


$(document).ready(function() {
    if (window.history && history.pushState) {
        historyedited = false;
        $(window).on('popstate', function(e) {
            if (historyedited) {
                loadProducts(location.pathname + location.search);
            }
        });
        doPager();
    }
});

function doPager() {
    $('.paging li a').click(function(e) {
        e.preventDefault();
        loadProducts($(this).attr('href'));
        history.pushState(null, null, $(this).attr('href'));
        historyedited = true;
    });
}

function loadProducts(url) {
    $('.small li').empty().load(url + ' .small', function() {
        doPager();
    });
}

It is working good at first click, but when I click 2, or 3, or 4 times the problem cames up. It makes multiple Ajax request and things are getting worser. What is wrong with my code?

When clicking on a new page you'll have to cancel the previous request first. You can't use .load() for this, so better use $.ajax instead. You could do it like this:

$(document).ready(function() {
    $('.paging li a').click(function(e) {
        e.preventDefault();

        // Cancel previous request if there is one
        if(typeof xhr !== 'undefined') {
            xhr.abort();
        }

        // Do the new request
        var xhr = $.ajax({
            url: $(this).attr('href') + '.small',
            success: function(data) {
                 $('.small li').html(data);
                 doPager();
            }
        });
    });
});

Try the folowing method

$(document).ready(function() {
if (window.history && history.pushState) {
    historyedited = false;$(window).on('popstate', function(e) {
        if (historyedited) {
            loadProducts(location.pathname + location.search);
        }
    });
}
$('.paging li a').click(function(e) {
    e.preventDefault();
    loadProducts($(this).attr('href'));
    history.pushState(null, null, $(this).attr('href'));
    historyedited = true;
});});


function loadProducts(url){
$('.small li').empty().load(url + ' .small');}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM