2012-01-25 37 views
11

我有一個頁面,基於按下一個按鈕,用戶動態加載的內容:保存頁面狀態重溫使用瀏覽器的後退按鈕

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

動態內容工作正常,我可以整天抓取網頁。但是,當您按照指向其他頁面的鏈接,然後按瀏覽器後退按鈕返回到頁面,該頁面將完全重置,就像沒有加載動態內容一樣。

我發誓我以前見過不同的行爲,但也許我瘋了。瀏覽器不應該保留頁面的狀態,而不是重新渲染它?編輯: 順便說一下,我使用的是Play!框架,如果這對此有任何影響。

回答

18

瀏覽器在第一次收到頁面時加載頁面。任何通過javascript完成的DOM修改都不會被保留。

如果你想保留修改,你將不得不做一些額外的工作。在修改DOM之後,使用稍後可以解析並重新創建修改的標識符更新url哈希值。無論何時載入頁面,您都需要檢查是否存在散列,並根據標識符進行DOM修改。

例如,如果您要動態顯示用戶信息。每當你顯示一個你會改變網址哈希像這樣:「#/ user/john」。無論何時加載頁面,您都需要檢查散列是否存在(window.location.hash),解析它並加載用戶信息。

+2

你會認爲,對於這樣一個基本的需要,它的工作有點不同。我想知道HTML5是否有適合我們的商店... – Indigenuity

+0

Cookie是另一種可能性。您可以在JavaScript中設置會話cookie。 – rustyx

1

epignosisx和Malcolm都是對的。它也被稱爲「深度鏈接」。我們在最近的Play應用程序中使用了JQuery Address Plugin來處理這個問題。

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

0

我用這個的技術是序列化狀態,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)); 
} 
相關問題