修复后退按钮问题加载更多分页样式

时间:2015-05-14 16:46:31

标签: javascript jquery ajax pagination infinite-scroll

HTML

<div class="moreButton">
        <a class="more" id="<?php echo htmlspecialchars($page);?>">More</a>
</div>

AJAX

$(function(){
    $('.more').live('click', function(){
        var page = $(this).attr('id');      //get the last id

        $.ajax({
            type    : 'GET',
            url     : 'functionality/js/paginate.php',
            data    : { page : page, per_page : per_page, last_page : last_page },
            beforeSend: function(){
                $('.more').html(img);
                if(history.pushState){
                   history.pushState(null, null, '#' + page);
                }else{
                   location.hash = '#' + page;
                }
            },
            success: function(data){
                $('.more').remove();
                $('.main-content').append(data);
            }
        });
    });
});

我实施了load_more分页风格。这里的问题是无限滚动的常见问题,当用户点击帖子并返回后退按钮时,他/她应该获得之前加载的帖子数量,但只加载初始帖子。我正在尝试根据我发现的谷歌搜索来整合history.pushState功能,但似乎没有让它工作。我在这里缺少什么?

2 个答案:

答案 0 :(得分:0)

使用浏览器历史记录保存状态有两个关键部分。 pushState函数允许您添加到历史堆栈(基本上就像转到新页面)。它还允许您将javascript对象存储为&#34;状态&#34;。当国家被弹出时,这将派上用场。离开堆栈(例如,按下浏览器&#34;&#34;后退&#34;按钮)。

浏览器抛出popstate事件,您可以使用该事件来确定浏览器是否返回到先前的状态。您可以使用window.onpopstate访问它。要查看哈希更改,您可以使用window.onhashchange

if ("onpopstate" in window) {
    window.onpopstate = function (event) {
        if (event.state && event.state.pageID) {
            fetchData(event.state.pageID);
        }
    };
}

if ("onhashchange" in window) {
    window.onhashchange = function () {
        if (location.hash) {
            fetchData(location.hash.substr(1));
        }
    };
}

function fetchData(pageID) {
    // Load some content
}

function saveState(pageID) {
    if (history.pushState) {
        history.pushState({ pageID: pageID }, null, "/page/" + pageID);
    } else {
        location.hash = pageID;
    }
}

答案 1 :(得分:0)

在这里,您需要定义一个函数来检查哈希更新,就像哈希更新(用户点击后退/前进按钮)一样,它应该根据URL更新页面数据。