ajax能夠實現頁面的無刷新操做,可是沒法前進與後退,淡出使用Ajax不利於SEO。現在,HTML5讓事情變得簡單。當執行ajax操做時,往瀏覽器history中塞入一個地址(使用pushState)(這是無刷新的),因而返回的試後,經過URL或其餘傳參咱們就能夠還原到ajax以前的模樣。javascript
屬性php
1. history.pushState(data, title [, url]):往歷史記錄堆棧頂部添加一條記錄;data會在onpopstate事件觸發時做爲參數傳遞過去;title爲頁面標題,當前全部瀏覽器都會 忽略此參數;url爲頁面地址,可選,缺省爲當前頁地址。html
2. history.replaceState(data, title [, url]) :更改當前的歷史記錄,參數同上。 html5
3. history.state:用於存儲以上方法的data數據,不一樣瀏覽器的讀寫權限不同。java
4. popstate事件:當用戶單擊瀏覽器的後退或者前進按鈕時觸發該事件。在事件處理函數中讀取觸發事件的事件對象的state屬性值,該屬性值即爲執行pushState方法時所使用的第一個參數值,其中保存了在向瀏覽器歷史記錄中添加記錄同步保存的對象。ajax
<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格式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.phpapp
<?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); } }); });