若是你要了解PJAX,請看:
AJAX + window.history.pushState/onpopstate (須要HTML5支持)
https://github.com/defunkt/jquery-pjax
我下面說的是錨點連接(書籤連接)這個方案:
AJAX + window.location.hash/onhashchange (兼容IE8)
拿首頁分頁連接來講:javascript
<a href="/index.php?page=3" onclick="page(3);return false;">3</a>
搜索引擎的爬蟲會根據href訪問/index.php?page=3獲取第3頁數據,利於SEO.
用戶在瀏覽器裏右鍵選擇"在新標籤頁中打開"也能正常訪問到/index.php?page=3.
若是用戶在頁面直接點擊連接,則觸發click事件,
由JS經過AJAX加載並渲染局部數據,
以及設置location.hash爲/index.php#/page/3.php
location.hash = "#/page/3";
瀏覽器可以自行記住location.hash歷史記錄,
咱們只需監聽location.hash改變的事件hashchange(支持IE8,不支持IE7/6)
就能實現用戶點擊瀏覽器返回按鈕時從新加載頁面的效果.html
$(window).on("hashchange", function(){ alert(location.hash); //假如輸出#/page/2 var arr = location.hash.split("/"); // ["#", "page", "2"] switch(arr[1]) { cace "page": ajax_page(arr[2]); //AJAX局部加載第2頁數據 //location.href = "/index.php?page="+arr[2]+"&"+new Date().getTime(); //直接訪問第2頁 break; case "post": ajax_post(arr[2]); //post.php?id=1024&ajax=1478791719965 break; } });
分頁:
index.php?page=3
index.php#/page/3
ajax_page(3); //index.php?page=3&ajax=1478791719965
文章頁:
post.php?id=1024
post.php#/id/1024
ajax_post(1024); //post.php?id=1024&ajax=1478791719965
URI中帶有參數ajax的請求,PHP返回JSON數據:java
{"title":"標題","main":"<div id=\"main\">正文(JS統計須要放這裏)<\/div>"}
參數ajax的內容是時間戳,避免瀏覽器使用緩存.
能夠考慮把參數ajax的內容設爲"年月日時分"的組合,讓數據在瀏覽器緩存1分鐘.
2016-08-01 08:06:00
2016-08-01 08:07:00
像PJAX同樣,ajax_page是用戶點擊觸發的,因此並不須要獲取keywords那些SEO的東西,只需更新標題和內容便可.jquery
<title>標題</title> <div id="main">正文(JS統計須要放這裏)</div> document.title = data["title"]; $("#main").html(data["main"]);