ajax与HTML5 history API实现无刷新跳转

一、ajax载入与浏览器历史的前进与后退

ajax可以实现页面的无刷新操作,但是无法前进与后退,淡出使用Ajax不利于SEO。如今,HTML5让事情变得简单。当执行ajax操作时,往浏览器history中塞入一个地址(使用pushState)(这是无刷新的),于是返回的试后,通过URL或其他传参我们就可以还原到ajax之前的模样。

二、温故知新

HTML4中的History API

属性

  1. length 历史的项数。javascript 所能管到的历史被限制在用浏览器的“前进”“后退”键可以去到的范围。本属性返回的是“前进”和“后退”两个按键之下包含的地址数的和。

方法

  1. back() 后退,跟按下“后退”键是等效的。
  2. forward() 前进,跟按下“前进”键是等效的。
  3. go() 用法:history.go(x);在历史的范围内去到指定的一个地址。如果 x < 0,则后退 x 个地址,如果 x > 0,则前进 x 个地址,如果 x == 0,则刷新现在打开的网页。history.go(0) 跟 location.reload() 是等效的。

HTML5中的History API

  1. history.pushState(data, title [, url]):往历史记录堆栈顶部添加一条记录;data会在onpopstate事件触发时作为参数传递过去;title为页面标题,当前所有浏览器都会 忽略此参数;url为页面地址,可选,缺省为当前页地址。

  2. history.replaceState(data, title [, url]) :更改当前的历史记录,参数同上。    

  3. history.state:用于存储以上方法的data数据,不同浏览器的读写权限不一样。

  4. popstate事件:当用户单击浏览器的后退或者前进按钮时触发该事件。在事件处理函数中读取触发事件的事件对象的state属性值,该属性值即为执行pushState方法时所使用的第一个参数值,其中保存了在向浏览器历史记录中添加记录同步保存的对象。

三、实例

<div class="container">
    <ul class="list">
        <li>
            <a href="http://localhost/demo/html5/index.php">测试1</a>
        </li>
        <li>
            <a href="http://localhost/demo/html5/index2.php">测试2</a>
        </li>
        <li>
            <a href="http://localhost/demo/html5/index3.php">测试3</a>
        </li>
    </ul>

    <div class="all-content">
        <ul class="content">
            <li>111</li>
            <li>222</li>
            <li>333</li>
        </ul>
    </div>
</div>

index.php,就是输出一个JSON格式

<?php
    $data = json_decode(file_get_contents("php://input"));
    header("Content-Type: application/json; charset=utf-8");
    echo ("[{"age" : 24, "sex" : "boy", "name" : "huangxueming"},{"age" : 26, "sex" : "boy", "name" : "huangxueming2"}]");
?>

index2.php

<?php
    $data = json_decode(file_get_contents("php://input"));
    header("Content-Type: application/json; charset=utf-8");
    echo ("[{"age" : 65, "sex" : "boy2", "name" : "huangxueming2"},{"age" : 26, "sex" : "boy", "name" : "huangxueming2"}]");
?>

index3.php

<?php
    $data = json_decode(file_get_contents("php://input"));
    header("Content-Type: application/json; charset=utf-8");
    echo ("[{"age" : 244, "sex" : "boy4", "name" : "huangxueming4"},{"age" : 264, "sex" : "boy4", "name" : "huangxueming4"}]");
?>

JS

$(function(){
    var ajax,
        currentState;
    $(".container li").unbind().bind("click",function(e){
        
        e.preventDefault();
        var target = e.target,
            url = $(target).attr("href");
        !$(this).hasClass("current") && $(this).addClass("current").siblings().removeClass("current");
        if(ajax == undefined) {
            currentState = {
                url: document.location.href,
                title: document.title,
                html: $(".content").html()
            };
        }
        ajax = $.ajax({
                type:"POST",
                url: url,
                dataType:"json",
                success: function(data){
                    var html = "";
                    if(data.length > 0) {
                        for(var i = 0, ilist = data.length; i < ilist; i++) {
                            html += "<li>" +data[i].age+ "</li>" + 
                                    "<li>" +data[i].name+ "</li>" +
                                    "<li>" +data[i].sex+ "</li>";
                        }
                        $(".content").html(html);
                    }
                    var state = {
                        url: url,
                        title: document.title,
                        html: $(".content").html()
                    };
                    history.pushState(state,null,url);
                }
        });
        
    });

    window.addEventListener("popstate",function(event){
        if(ajax == null){
                return;
            }else if(event && event.state){
                document.title = event.state.title;
                $(".content").html(event.state.html);
            }else{
                document.title = currentState.title;
                $(".content").html(currentState.html);
            }
    });
 });