2013年9月12日 星期四

Ajax 不需重整 直接修改url

在做網頁的時候,如果只是想記錄網頁url狀態,當refresh的時候可以記錄當時狀態,或者是重返上一頁可以顯示上一頁的資訊,除了透過 location.href 整個網頁重新load外,也可以利用html5的功能:history.pushState() 或者是 history.replaceState()。



以前refresh頁面,比較常用下面這種<<index有做相對應page導向之網頁,所以這裡只用url後面的變數表示>>
location.href = ?page=hello&a=1 ;
但是這種會全部refresh,所以在html5就出現了history.pushState() 這個方法。
history.pushState(0, 'url', '?page=hello&a=1);

其他瀏覽器都可以使用。可是好景不常,有ie這個大魔王存在,必須要ie10以上才有完全支援這種方式,所以必須要靠網路上好心網友寫好的history.js檔
https://github.com/devote/HTML5-History-API/

使用方式:
<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="history.js"></script>
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript">
        $(function() {
            $("a").click(function() {
                history.pushState( null, null, this.href ); //改變網址的url
                return false;
            });

            $( window ).bind( "popstate", function( e ) {
//使用history回上一頁或者是F5重整得出url
                var returnLocation = history.location || document.location;
                alert( "We returned to the page with a link: " + returnLocation.href );
            });
        });
        </script>
    </head>
    <body>
        <a href="/mylink.html">My Link</a>
        <a href="/otherlink.html">Other Link</a>
    </body>
</html>



另外如何偵測瀏覽器是否支援 replaceState
if(window.history.replaceState) {
    //Your code

}


雖然讓IE9具有history.pushState()這功能,但是如果網頁目錄藏很深,或者是url後面有其他字串,操作回上一頁,或者是重整的話,就會跑到錯誤的路徑,所以暫時解決的方式還是先偵測如果此狀態就回到refresh吧!


網路上有作者詳細描述關於此之演變史
http://rettamkrad.blogspot.tw/2013/04/ajaxandhistoryapi.html

參考資料:
https://github.com/devote/HTML5-History-API/ (本文主要參考處)
http://stackoverflow.com/questions/9645920/history-js-the-correct-implementation/

沒有留言:

張貼留言