在滚动时使用ajax加载内容

时间:2010-07-19 17:59:43

标签: javascript jquery ajax scroll

我正在使用jQuery Tools Plugin作为图片滑块(image here),但由于图像数量很大,我需要一次加载几个。因为它是javascript编码的,所以我不知道滚动位置。我想在最后一张图片显示或类似的东西时加载它们。我不知道我放在哪里和事件监听器都没有。

这是我的代码http://jsfiddle.net/PxGTJ/

请给我点亮一点!

5 个答案:

答案 0 :(得分:4)

我只需使用jQuery Tools的API,onSeek方法中的scrollable()参数。

就像那样

$(".scrollable").scrollable({
    vertical: true,
    onSeek: function() {
        row = this.getIndex();
        // Check if it's worth to load more content
        if(row%4 == 0 && row != 0) {
            var id = this.getItems().find('img').filter(':last').attr('id');
            id = parseInt(id);
            $.get('galeria.items.php?id='+id, null, function(html) {
                $('.items').append(html);
            });
        }
    }
}); 

答案 1 :(得分:3)

可以通过以下方式进行:

//When the DOM is ready...
$(document).ready(function() {

   //When the user scrolls...
   $(window).scroll(function() {
       var tolerance = 800,
           scrollTop = $(window).scrollTop();

       //If the the distance to the top is greater than the tolerance...
       if(scrollTop > tolerance) {

           //Do something. Ajax Call, Animations, whatever.

       }
   }) ;
});

这应该可以解决问题。

编辑:因为你没有使用原生卷轴,我们必须对代码做一些修复:

//When the DOM is ready...
$(document).ready(function() {

   //When the user scrolls...
   $("div.scrollable").find(".next").click(function() {
       var tolerance = 800,
           // The absolute value of the integer associated 
           // to the top css property
           scrollTop = Math.abs(parseInt($("div.items").css("top")));

       //If the the distance to the top is greater than the tolerance...
       if(scrollTop > tolerance) {

           //Do something. Ajax Call, Animations, whatever.

       }
   }) ;
});

答案 2 :(得分:0)

尝试这样的事情

$('#scrollable').find('img:last').load(function() {
        //load the content  
});

或找到最后图片的offset位置/位置,并在scrolling <到达偏移位置时尝试加载内容/ p>

HTML

<div>
   <br><br><br><br><br><br><br><br><br><br><br><br><br><br>
   <br><br><br><br><br><br><br><br><br><br><br><br><br><br>
   <span>Hello !!</span>
   <br><br><br><br><br><br><br><br><br><br><br><br><br><br>
   <br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</div> 

一些 CSS

div {
    width:200px;
    height:200px;
    overflow:scroll;
}

Javascript

$(document).ready(function() {
     $('div').scroll(function() {
         var pos    = $('div').scrollTop();
         var offset = $('span').offset().top;
         if(pos >= offset ) {
           alert('you have reached your destiny');
         }
   });
});    

这是一个快速演示 http://jsfiddle.net/8QbwU/

虽然Demo没有满足您的全部要求,但我相信它会让您some light继续进行:)

答案 3 :(得分:0)

首先,您需要为此使用jQuery

其次,在页面上放置占位符以包含您的数据。

<table id="dataTable" class="someClass" style="border-collapse: collapse;">
    <colgroup>
        <col width="12%" />
        <col width="12%" />
        <col width="12%" />
        <!-- Define your column widths -->
    </colgroup>
</table>

您需要在Web服务中编写自己的GetData方法,但这是一般的想法(并从页面加载调用Refresh();)

function Refresh() {
    var getData = function(callback, context, startAt, batchSize) {
        MyWebservice.GetData(
            startAt,   //What record to start at (1 to start)
            batchSize, //Results per page
            3,         //Pages of data
            function(result, context, method) {
                callback(result, context, method);
            },
            null,
            context
        );
    };

    $('#dataTable').scrolltable(getData);
}

将getData函数变量传递给scrolltable插件,在滚动表时将根据需要调用它。回调和上下文被传入,并由插件用于管理您正在操作的对象(上下文)和Web的异步性质(回调)

GetData(注意案例)webmethod需要返回一个包含一些关键信息的JSON对象,服务器端代码如何做到这一点取决于您,但此插件所需的对象如下。 Prior和Post数据用于触发何时加载更多数据,基本上,您可以滚动浏览中间/活动页面,但是当您开始查看前一页或后一页中的数据时,我们将需要获取更多数据

    return new {
        // TotalRows in the ENTIRE result set (if it weren't paged/scrolled)
        TotalRows = tableElement.Element("ResultCount").Value,
        // The current position we are viewing at
        Position = startAt,
        // Number of items per "page"
        PageSize = tableElement.Element("PageSize").Value,
        // Number of pages we are working with (3)
        PageCount = tableElement.Element("PageCount").Value,
        // Data page prior to active results
        PriorData = tbodyTop.Html(),
        // Data to display as active results
        CurrentData = tbodyCtr.Html(),
        // Data to display after active results
        PostData = tbodyBot.Html()
    };

接下来是插件本身

/// <reference path="../../js/jquery-1.2.6.js" />
(function($) {
    $.fn.scrolltable = function(getDataFunction) {
        var setData = function(result, context) {
            var timeoutId = context.data('timeoutId');
            if (timeoutId) {
                clearTimeout(timeoutId);
                context.data('timeoutId', null);
            }

            var $table = context.find("table");
            var $topSpacer = $table.find('#topSpacer');
            var $bottomSpacer = $table.find('#bottomSpacer');

            var $newBodyT = $table.children('#bodyT');
            var $newBodyC = $table.children('#bodyC');
            var $newBodyB = $table.children('#bodyB');

            var preScrollTop = context[0].scrollTop;

            $newBodyT.html(result.PriorData);
            $newBodyC.html(result.CurrentData);
            $newBodyB.html(result.PostData);

            var rowHeight = $newBodyC.children('tr').height() || 20;
            var rowCountT = $newBodyT.children('tr').length;
            var rowCountC = $newBodyC.children('tr').length;
            var rowCountB = $newBodyB.children('tr').length;

            result.Position = parseInt(result.Position);
            $newBodyC.data('firstRow', result.Position);
            $newBodyC.data('lastRow', (result.Position + rowCountC));
            context.data('batchSize', result.PageSize);
            context.data('totalRows', result.TotalRows);

            var displayedRows = rowCountT + rowCountC + rowCountB;
            var rowCountTopSpacer = Math.max(result.Position - rowCountT - 1, 0);
            var rowCountBottomSpacer = result.TotalRows - displayedRows - rowCountTopSpacer;

            if (rowCountTopSpacer == 0) {
                $topSpacer.closest('tbody').hide();
            } else {
                $topSpacer.closest('tbody').show();
                $topSpacer.height(Math.max(rowCountTopSpacer * rowHeight, 0));
            }

            if (rowCountBottomSpacer == 0) {
                $bottomSpacer.closest('tbody').hide();
            } else {
                $bottomSpacer.closest('tbody').show();
                $bottomSpacer.height(Math.max(rowCountBottomSpacer * rowHeight, 0));
            }

            context[0].scrollTop = preScrollTop;  //Maintain Scroll Position as it sometimes was off
        };

        var onScroll = function(ev) {
            var $scrollContainer = $(ev.target);

            var $dataTable = $scrollContainer.find('#dataTable');
            var $bodyT = $dataTable.children('tbody#bodyT');
            var $bodyC = $dataTable.children('tbody#bodyC');
            var $bodyB = $dataTable.children('tbody#bodyB');

            var rowHeight = $bodyC.children('tr').height();
            var currentRow = Math.floor($scrollContainer.scrollTop() / rowHeight);
            var displayedRows = Math.floor($scrollContainer.height() / rowHeight);

            var batchSize = $scrollContainer.data('batchSize');
            var totalRows = $scrollContainer.data('totalRows');

            var prevRowCount = $bodyT.children('tr').length;
            var currRowCount = $bodyC.children('tr').length;
            var postRowCount = $bodyB.children('tr').length;

            var doGetData = (
                                (
                                    (currentRow + displayedRows) < $bodyC.data('firstRow')                      //Scrolling up
                                    && (($bodyC.data('firstRow') - prevRowCount) > 1)                           // ...and data isn't already there
                                )
                            ||
                                (
                                    (currentRow > $bodyC.data('lastRow'))                                       //Scrolling down
                                    && (($bodyC.data('firstRow') + currRowCount + postRowCount) < totalRows)    // ...and data isn't already there
                                )
                            );

            if (doGetData) {
                var batchSize = $scrollContainer.data('batchSize');

                var timeoutId = $scrollContainer.data('timeoutId');
                if (timeoutId) {
                    clearTimeout(timeoutId);
                    $scrollContainer.data('timeoutId', null);
                }

                timeoutId = setTimeout(function() {
                    getDataFunction(setData, $scrollContainer, currentRow, batchSize);
                }, 50);

                $scrollContainer.data('timeoutId', timeoutId);
            }
        };

        return this.each(function() {
            var $dataTable = $(this);

            if (!getDataFunction) 
                alert('GetDataFunction is Required');

            var batchSize = batchSize || 25;
            var outerContainerCss = outerContainerCss || {};

            var defaultContainerCss = {
                overflow: 'auto',
                width: '100%',
                height: '200px',
                position: 'relative'
            };

            var containerCss = $.extend({}, defaultContainerCss, outerContainerCss);

            if (! $dataTable.parent().hasClass('_outerContainer')) {
                $dataTable
                    .wrap('<div class="_outerContainer" />')
                    .append($('<tbody class="spacer"><tr><td><div id="topSpacer" /></td></tr></tbody>'))
                    .append($('<tbody id="bodyT" />'))
                    .append($('<tbody id="bodyC" />'))
                    .append($('<tbody id="bodyB" />'))
                    .append($('<tbody class="spacer"><tr><td><div id="bottomSpacer" /></td></tr></tbody>'));
            }

            var $scrollContainer = $dataTable.parent();

            $scrollContainer
                .css(containerCss)
                .scroll(onScroll);

            getDataFunction(setData, $scrollContainer, 1, batchSize);
        });
    };
})(jQuery);

你可能需要调整一些东西。我刚刚将它转换为jQuery插件,它可能仍然有点小故障。

答案 4 :(得分:-1)

$(".scrollable").scrollable({
    vertical: true,
    onSeek: function() {
        row = this.getIndex();
        // Check if it's worth to load more content
        if(row%4 == 0 && row != 0) {
            var id = this.getItems().find('img').filter(':last').attr('id');
            id = parseInt(id);
            $.get('galeria.items.php?id='+id, null, function(html) {
                $('.items').append(html);
            });
        }
    }
});