jQuery AJAX请求加载两次 [英] Jquery AJAX-request loading twice

查看:440
本文介绍了jQuery AJAX请求加载两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个无限滚动,当滚动条到达页面底部时,该滚动条会从数据库中获取结果.除了一件小事,一切都很好.如果我快速向下滚动,它将两次获取结果,就好像该函数执行了两次一样.

I'm building an infinite Scroll wich fetches results from a database when the scroller hits the bottom of the page. It's all working fine except for one small thing; it is fetching the results twice if I scroll down fast, as if the function is executed twice.

这是我的jQuery代码:

Here is my jQuery code:

$(window).scroll(function () {
    if($(window).scrollTop() == $(document).height() - $(window).height()) {
        var ID = $('.stbody:last').attr('id').match(/stbody(\d+)/)[1];
        $('#loader').show();
        $.ajax({
            url: "ajax_loadmore.php?lCom=" + ID,
            success: function (result) {
                if(result) {
                    $('#moreComments').append(result);
                    $('#loader').hide();
                } else {
                    $('#loader').hide();
                }
            }
        });
    }
});

推荐答案

作为@JamWaffles答案的补充:

As an addition to @JamWaffles answer:

您可以仅使用return;退出该函数,而不用调用request.abort();.否则,您将对相同的数据发出两个AJAX请求=服务器不必要的负载.然后,您应该在成功和错误回调中使用request = null;重置请求对象.

You may just exit the function with return; instead of calling request.abort();. Otherwise you will make two AJAX requests for the same data = unnecessary load for your server. You should then, however, reset the request object with request = null; in the success and error callback.

PS.会将其作为评论发布,但我不能.

PS. Would post this as a comment, but I can't.

这篇关于jQuery AJAX请求加载两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆