【问题标题】:Handle multiple Ajax request on pagination在分页上处理多个 Ajax 请求
【发布时间】:2018-02-12 00:53:05
【问题描述】:

检索数据:

<div class="manifestations">
  @include('data.php')
</div>

这是我的代码:

<script>
    $(window).on('hashchange', function() {
        if (window.location.hash) {
            var page = window.location.hash.replace('#', '');
            if (page == Number.NaN || page <= 0) {
                return false;
            } else {
                getManifestations(page);
            }
        }
    });


    $(document).ajaxStop(function () {
        $('#spinCard').hide();
    });

    $(document).ajaxStart(function () {
        $('#spinCard').show();
    });

    app.ready(function(){
        $(document).on('click', '.pagination a', function (e) {
            getManifestations($(this).attr('href').split('page=')[1]);
            e.preventDefault();
        });
    });
    function getManifestations(page) {
        $.ajax({
            url : '?page=' + page,
            dataType: 'json',
        }).done(function (data) {
            $('.manifestations').html(data);
            location.hash = page;
        }).fail(function () {
           alert('Manifestations could not be loaded.');
        });
    }
</script>

如果用户在下一个 ajax 上连续单击多次,则会在页码之间不断跳转,例如 #5 #6 #5 #6 #5 ... 有没有办法防止这种情况发生?

ps 删除这个:

$(window).on('hashchange', function() {
        if (window.location.hash) {
            var page = window.location.hash.replace('#', '');
            if (page == Number.NaN || page <= 0) {
                return false;
            } else {
                getManifestations(page);
            }
        }
    });

防止发送多个请求是否有任何解决方案可以修改上述代码并使其一次发送一个请求

【问题讨论】:

    标签: jquery ajax pagination


    【解决方案1】:

    防止这种情况的一种方法是在第一次调用完成之前不允许再进行一次 ajax 调用

     function getManifestations(page) {
        if(! $('#spinCard').hasClass('data-loading')) {
            $('#spinCard').addClass('data-loading')
           $.ajax({
                url : '?page=' + page,
                dataType: 'json',
            }).done(function (data) {
                $('.manifestations').html(data);
                location.hash = page;
            }).fail(function () {
               alert('Manifestations could not be loaded.');
            }).always(function () {
                $('#spinCard').removeClass('data-loading')
            });
          }
        }
    

    【讨论】:

    • 为此使用全局变量并不是最佳选择。使用具有更多上下文的东西,例如在相关元素上“加载”的 CSS 类。或者getManifestations() 中的闭包变量。此外,您总是想要重新设置变量,因此在.always() 回调中而不是在.done().fail() 中执行更有意义。
    • 根据 cmets 更新,谢谢。
    猜你喜欢
    • 2013-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-20
    • 2014-01-07
    • 1970-01-01
    • 2019-08-02
    相关资源
    最近更新 更多