【问题标题】:Preserve page state for revisiting using browser back button保留页面状态以使用浏览器后退按钮重新访问
【发布时间】:2012-02-19 01:24:44
【问题描述】:

我有一个基于用户按下按钮动态加载内容的页面:

${document).ready(function)
{
    $("#myButton").click(function()
    {
        $("#dynamicDiv").load("www.example.com");
    });
}

动态内容运行良好,我可以整天抓取页面。但是当你点击一个链接到另一个页面后,然后按浏览器返回按钮返回到该页面,页面将完全重置,就好像没有加载任何动态内容一样。

我发誓我以前见过不同的行为,但也许我疯了。浏览器不应该保留页面的状态,而不是重新渲染它吗?

编辑: 顺便说一句,我正在使用 Play!框架,如果这对此有任何影响。

【问题讨论】:

    标签: javascript jquery ajax playframework browser-history


    【解决方案1】:

    浏览器加载第一次收到的页面。任何通过 javascript 完成的 DOM 修改都不会被保留。

    如果您想保留修改,您将不得不做一些额外的工作。修改 DOM 后,使用标识符更新 url 哈希,以后可以解析并重新创建修改。每当加载页面时,您都需要检查是否存在散列并根据标识符进行 DOM 修改。

    例如,如果您正在动态显示用户信息。每次显示一个时,您都会将 url 哈希更改为如下所示:“#/user/john”。每当页面加载时,您需要检查哈希是否存在(window.location.hash),解析它并加载用户信息。

    【讨论】:

    • 您会认为,对于这样的基本需求,它的工作方式会有所不同。我想知道 HTML5 是否对我们有什么不同...
    • Cookie 是另一种可能性。您可以在 JavaScript 中设置会话 cookie。
    • 一切都很好,但如何真正解析和加载“用户”信息?
    【解决方案2】:

    实现浏览器返回功能很困难。 使用 jquery.history.js 之类的插件会更容易。

    http://tkyk.github.com/jquery-history-plugin/

    【讨论】:

      【解决方案3】:

      epignosisx 和 Malcolm 都是对的。它也被称为“深度链接”。我们在最近的 Play 应用程序中使用了 JQuery 地址插件来处理这个问题。

      http://www.asual.com/jquery/address/

      【讨论】:

        【解决方案4】:

        我为此使用的一种技术是将状态序列化为 JSON,将其存储在哈希字符串中,然后在导航回页面时将其读回。已在 IE10+、Firefox、Chrome 中测试。

        例子:

        // On state change or at least before navigating away from the page, serialize and encode the state
        // data you want to retain into the hash string
        
        window.location.hash = encodeURIComponent(JSON.stringify(myData));
        
        // If navigating away using Javascript, be sure to use window.location.href over window.location.replace
        
        window.location.href = '/another-page-url'
        
        ....
        
        // On page load (e.g. in an init function), if there is data in the #hash, overwrite initial state data
        // by decoding and parsing the JSON string
        
        if (window.location.hash) {
        
            // Read the hash string omitting the # prefix
        
            var hashJson = window.location.hash.substring(1);
        
            // Restore the deserialized data to memory
        
            myData = JSON.parse(decodeURIComponent(hashJson));
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-07-18
          • 2017-06-25
          • 1970-01-01
          • 2012-12-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多