Ajax和后退按钮.哈希更改,但上一页的状态存储在哪里

Ajax and back button. Hash changes, but where is previous page state stored?

本文关键字:一页 状态 在哪里 存储 按钮 哈希更 Ajax      更新时间:2023-09-26

我正试图让ajax与后退按钮一起工作,但缺少一些核心内容。以前的页面状态存储在哪里?

情况1:

点击"让我变红"。ajax事件发生,页面变红。Hash=#red

点击"让我变黄"。ajax事件发生,页面变黄。Hash=#黄色

单击后退按钮。哈希现在又回到了#red。但我也希望页面是红色的。它仍然是黄色的。

情况2:

点击"让我变红"。ajax事件发生,页面变红。Hash=#red

单击"转到其他站点"。它进入谷歌。

单击后退按钮。我们回到了网站,hash=#red,但我也希望页面是红色的!

<!DOCTYPE html>
<html>
<style>
    .red{background:red}
    .yellow{background:yellow}
</style>
<head>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script type="text/javascript">
    $(function(){
        $('.ajax_thing').click(function(){
            location.hash=$(this).attr('action_type');
            return false
        })
        var originalTitle=document.title
        function hashChange(){
            var page=location.hash.slice(1)
            if (page!=""){
                $('#content').load(page+".html #sub-content")
                document.title=originalTitle+' – '+page
            }
        }
        if ("onhashchange" in window){ // cool browser
            $(window).on('hashchange',hashChange).trigger('hashchange')
        }else{ // lame browser
            var lastHash=''
            setInterval(function(){
                if (lastHash!=location.hash)
                    hashChange()
                lastHash=location.hash
            },100)
        }
    })
    </script>
</head>
<body>
<menu>
       <li><a class="ajax_thing" id = "red_action" action_type="red">Make me red</a></li>
        <li><a class="ajax_thing" id = "yellow_action" action_type="yellow">Make me yellow</a></li>
</menu>
        <li><a href = "http://www.google.com">Go to other site</a></li>
</body>
</html>
<script>
$("#red_action").click(function(e) {
  // ajax here. on success:
    $("body").removeClass("yellow");
    $("body").addClass("red");
})
$("#yellow_action").click(function(e) {
  // ajax here. on success:
    $("body").removeClass("red");
    $("body").addClass("yellow");
})
</script>

与其使用JavaScript驱动URL,不如让URL驱动JavaScript。让window.onhashchange事件处理程序来完成所有工作。其他一切都应该改变散列。

您甚至不需要链接的点击处理程序,只需将url设置为正确的哈希即可:

<a href="#red">Red</a>

然后,您的hashchange处理程序将处理其余部分:

function hashChange() {
    var page = location.hash.slice(1);
    if (page) {
        $('#content').load(page+".html #sub-content");
        document.title = originalTitle + ' – ' + page;
        switch (page) {
            // page specific functionality goes here
            case "red":
            case "yellow":
                $("body").removeClass("red yellow").addClass(page);
                break;
        }
    }
}

更改哈希的唯一原因是,如果您希望能够返回页面,并让它根据URL加载相同的状态。所以,您已经有了让URL驱动JavaScript的要求,对吧?否则,你为什么要更改哈希?将功能从单击处理程序移到hashchange事件中只会简化事情。

使用AJAX时,使用history.pushState 手动更新历史记录非常重要

然后创建一个函数来测试onopstate事件,并根据需要更新内容。

https://developer.mozilla.org/en-US/docs/Web/Guide/DOM/Manipulating_the_browser_history