2010-01-24 49 views
0

嗨,大家好我已經開發了一個整潔的搜索功能的谷歌地圖應用程序 - 但是我注意到,我想有一些像facebook傢伙做的一樣,有一個硬鏈接到由ajax查詢生成的頁面。例如你點擊Facebook上的鏈接,它附加到當前的網址,你可以複製粘貼新的網址來獲得請求的頁面...我如何實現這樣的事情...Url尋找Ajax請求的結果

+0

你在說要爲網址添加散列嗎?正如在http:// domain/path?query#hash的最後部分一樣 – Atli 2010-01-24 09:09:23

回答

1

您可以使用從withing JavaScript中location.hash(URL的#後的部分)設置 「硬鏈接」。這不會導致頁面重新加載,就像更改location.href一樣,但是您可以獲取該值並在JavaScript中使用它。

考慮這個例子:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 
<head> 
    <title>Hash test</title> 
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"> 
    <script type="text/javascript"> 
    window.onload = function() { 
     // The substring(1) removes the # from the hash. 
     var hash = window.location.hash.substring(1); 

     // Use a default value if no has was passed. 
     if(hash == '') { 
      hash = 'Nothing'; 
     } 

     // Use the value. 
     document.getElementById('selection').innerHTML = hash; 
    } 

    /** Sets the hash and updates the page value */ 
    function setHash(newHash) { 
     window.location.hash = newHash; 
     document.getElementById('selection').innerHTML = newHash; 
    } 
    </script> 
</head> 
<body> 
    <div> 
     <div> 
      <a href="javascript: void();" onclick="setHash('page1');">Page 1</a> | 
      <a href="javascript: void();" onclick="setHash('page2');">Page 2</a> | 
      <a href="javascript: void();" onclick="setHash('page3');">Page 3</a> 
     </div> 
     <div> 
      You have selected: <span id="selection">...</span> 
     </div> 
    </div> 
</body> 
</html> 

當你點擊頁面鏈接之一,location.hash改變,瀏覽器的URL進行更新,並在頁面中使用的值被改變。如果用戶直接從地址欄中複製URL或對其進行書籤,則當再次請求URL時,所選頁面將被重新加載。

2

聽起來像你想要的使用可用於重新訪問當前狀態的頁面的鏈接更新瀏覽器的URL。這可以通過操縱瀏覽器歷史來完成。

的一個很好的解決辦法是:

真正簡單的歷史

http://code.google.com/p/reallysimplehistory/

真正簡單的歷史是一個輕量級的 JavaScript庫的書籤和瀏覽器歷史記錄中 阿賈克斯管理 /DHTML應用程序。 RSH 將應用程序數據序列化在 內部JavaScript高速緩存中,以便 書籤和後退按鈕可以是 用於將您的應用程序返回到以前的狀態 。

退房這個很好的例子:

http://www.justise.com/2009/01/26/enabling-the-back-button-in-ajax-applications/