之前的案子若想要達成 ajax 撈取 content,並且擁有自己的網址以便使用者可以直接進入該連結的話,我們會使用 hashbang 的作法,也就是帶入 #!,在由 javascript 端解析 url 的部分並撈取實際的 content,這樣的缺點很多,除了網址相當醜以外,也會多送一些 request,也不支援上下頁,後來 HTML5 盛行後,由 Google 提出了 pushState 解決方案,可以保留原本的網址,又簡單克服上述的問題,今天使用 browserstate/history.js 來做一個示範。
history.php
<?php
$name = 'a';
if (isset($_GET['name'])) {
$rand = rand(1, 3);
sleep($rand);
$name = $_GET['name'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script src="https://code.jquery.com/jquery-1.11.2.js"></script>
<script src="assets/jquery/jquery.history.js"></script>
<script src="assets/js/history.js"></script>
</head>
<body>
<a href="history.php?name=a">a</a>
<a href="history.php?name=b">b</a>
<div id="content">I am <?php echo $name; ?></div>
</body>
</html>
history.js
$(function() {
var content = $('#content');
$('a').on('click', function(e) {
History.pushState(null, $(this).text(), $(this).attr('href'));
return false;
});
History.Adapter.bind(window, 'statechange', function() {
var state = History.getState();
content.html('loading...');
$.get(state.url, function(response) {
content.html($(response).filter('#content').html());
});
});
});
當我們第一次執行任何一個 PHP 頁面時,可以直接獲得該頁的正確資料,如果是透過超連結點選的話,我們透過 ajax 抓取該頁面,並且 filter 出我們要置換的內容,對瀏覽器來說 HTML 只是文字而已,所以沒有 render 的圖片部分便不會吃到頻寬,一舉數得,相容性的問題就交給套件解決吧。
沒有留言:
張貼留言