简体   繁体   English

防止多个Ajax请求(使用pushstate分页)

[英]Prevent multiple Ajax request (pagination with pushstate)

There I had a problem with ajax pagination with HTML API Pushstate. 在那里我遇到了使用HTML API Pushstate进行ajax分页的问题。

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. 它在第一次点击时效果很好,但当我点击2,或3或4次时,问题出现了。 It makes multiple Ajax request and things are getting worser. 它产生了多个Ajax请求,而且事情变得越来越糟糕。 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. 你不能使用.load(),所以最好使用$ .ajax。 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');}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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