在使用ajax请求加载页面时,需要浏览器的正常后退按钮功能

时间:2013-04-29 15:19:09

标签: php jquery html ajax

我在php中开发Web应用程序,并使用 ajax请求从服务器获取页面 单击菜单选项卡上的示例ajax从服务器请求页面并将其加载到 index.php 的特定 HTMl div 中。因此,所有页面总是进入 index.php特定的htmi div。

因此,点击浏览器后退按钮,它始终保持默认页面。如何启用浏览器后退/前进按钮功能,以便它保持以前的页面状态

2 个答案:

答案 0 :(得分:0)

正如评论中所述,HTML5历史记录API提供了您正在寻找的功能,但如果您必须支持浏览器而不保证这些浏览器会支持历史记录API,请查看jQuery BBQ plugin ,它会让你到达你需要去的地方。要记住的重要一点是,您将使用URL主题标签来记录“页面加载”,它们只是真正的ajax加载。

答案 1 :(得分:0)

这样的事情可以解决问题,但我还没有测试过:

(function($, window) {
    function supports_history_api() {
        return !!(window.history && history.pushState);
    }

    if (!supports_history_api()) { return; }  // Doesn't support so return

    function swapContent(href) {
        $.ajax({
            url: href,
            cache: false
        }).done(function( data ) {
            var parser = $("#parser"); //Some empty and hidden element for parsing
            parser.html(data);

            var parsed = parser.find(".container").contents(), //Get the loaded stuff
                realContainer = $(".container").first(); //This one wasn't loaded

            realContainer.html(parsed);
            parser.contents().remove(); //Empty the div again
        });
    }

    $(".aTag").on("click", function(e) { //Select the links to do work on
        var href = $(this).attr("href");
        swapContent(href);
        e.preventDefault();
        history.pushState(null, null, href); //Push state to history, check out HTML 5 History API
    });

    window.onpopstate = function() {
        swapContent(location.href);
    };
})(jQuery, window);

一些HTML:

<div class="container">
    <a class="aTag" href="tiles_1.html"><img src="img/tiles_1.jpg" /></a>
    <a class="aTag" href="tiles_2.html"><img src="img/tiles_2.jpg" /></a>
    <a class="aTag" href="tiles_3.html"><img src="img/tiles_3.jpg" /></a>
    <a class="aTag" href="tiles_4.html"><img src="img/tiles_4.jpg" /></a>
</div>

//Loaded content gets pushed here for parsing
<div id="parser" style="display:none;"></div>