ajax+html5 pushState 技术实现页面局部刷新

经常玩google+,对于前端不太内行的我来说也感觉很好奇,google+是怎么做到局部刷新的?在网上一查,无意见看到有人说google 是使用html5 的一个API :pushState() 技术来实现的。

话不多说,直接上代码 :

<div id="content">
    
</div>

<script type="text/javascript">
    $(document).ready(function(){
        $("a").live('click',function(e){
             var href = $(this).attr('href');
             $.ajax({
                type: $(this).attr('method'),
                url: href,
                success: function(response){
                    $("#content").html(response);
                }
              
            });
            history.pushState('', 'New URL: '+href, href);
            e.preventDefault();
        });
    });
</script>

如果不知道具体作用是什么,就试着把红色那一行注释掉,刷新页面,仔细看URL地址。会发现它的不同。

通常使用Ajax来局部刷新页面 ,URL是不会改变的。但是history.pushState可以改变浏览器的URL历史,在ajax取得数据之后,可以更改页面的URL地址 。具体其它资料可以查看:

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

posted @ 2012-11-21 14:17  notewo  阅读(2092)  评论(0编辑  收藏  举报