首页 > 解决方案 > Django Infinite Scroll 没有运行 Ajax 的东西

问题描述

我已经使用了本教程并在 django 中实现了无限滚动并加载了页面。

但是,我的 Ajax 调用仅在第一页加载中有效,在随后的延迟加载中无效。我已经按照这个答案使用 $items.each.... 代码块。

但使用上述方法后,现在航点不再加载页面,我卡在第一页本身(Ajax 调用正在工作)。删除代码后,延迟加载能够加载后续页面。我正在使用带有 Django 3 的 Bootstrap 4。有什么建议吗?

我正在添加阻止延迟加载的脚本。

<script src="{% static 'js/jquery.waypoints.min.js' %}"></script>
<script src="{% static 'js/infinite.min.js' %}"></script>
<script>
$(document).ready(function() {
    var infinite = new Waypoint.Infinite({
      element: $('.infinite-container')[0],
      onBeforePageLoad: function () {
        $('.loading').show();
      },
      onAfterPageLoad: function ($items) {
        $('.loading').hide();
        $items.each(function(){
            $(this).find('.like').on('click', likecommentevent);
        }
      }
    });
});
</script>

编辑:备用更新,但这不是我需要的

我尝试了上面 onAfterPageLoad 的替代方法,并且延迟加载有效。但是现在 Ajax 调用被调用了两次或更多。

onAfterPageLoad: function ($items) {
        $('.loading').hide();
        $('.like').on('click', likecommentevent);
      }

标签: jquerydjangoajaxdjango-templatesdjango-pagination

解决方案


<script src="{% static 'js/jquery.waypoints.min.js' %}"></script>
<script src="{% static 'js/infinite.min.js' %}"></script>
<script>
$(document).ready(function() {
var infinite = new Waypoint.Infinite({
  element: $('.infinite-container')[0],
  onBeforePageLoad: function () {
    $('.loading').show();
  },
  onAfterPageLoad: function ($items) {
    $('.loading').hide();
    $items.find('.like').on('click', likecommentevent);
  }
});
});
</script>

进一步扩展这likecommentevent是一个存储有函数的值。(我的行话远非专业)它likecommentevent来自哪里,它存储什么?它可能看起来像这样:这类似于 upvote/downvote 系统。

var likecommentevent = function(event){

var answerid=$(this).data('answer');
        // Ajax
        $.ajax({
            url:"/save-downvote",
            type:"post",
            data:{
                answerid:answerid,
                csrfmiddlewaretoken:"{{csrf_token}}"
            },
            dataType:'json',
            success:function(res){
                var _prevupvote=$(".downvote-count-"+answerid).text();
                if(res.bool==true){
                    $(".downvote-count-"+answerid).text(parseInt(_prevupvote)+1);
                }
            }
        });
 }

无论你有什么功能,以这种方式存储并传入onAfterLoad:function($items){ ##here## }


推荐阅读