个人博客

A web front-end programmer's personal blog.

history 实现无刷新更改url和页面内容

在访问google plus网易m站时,细心的用户也许会发现页面之间的点击是通过ajax异步请求的,同时页面的URL发生了了改变。并且能够很好的支持浏览器的前进和后退。不禁让人想问,是什么有这么强大的功能呢?

HTML5里引用了新的API,就是history.pushState和history.replaceState,就是通过这个接口做到无刷新改变页面URL的。

对应history.pushState和history.replaceState的具体用法可以参考下面这几篇文章:

传统的ajax的问题

  • 虽然ajax可以无刷新改变页面内容,但无法改变页面URL
  • 为了更好的可访问性,内容发生改变后,改变URL的hash。但是hash的方式不能很好的处理浏览器的前进、后退等问题 有的浏览器引入了onhashchange的接口,不支持的浏览器只能定时去判断hash是否改变
  • ajax的使用对搜索引擎很不友好,往往蜘蛛爬到的区域是空的

为了解决传统ajax带来的问题,HTML5里引入了新的API,即:history.pushState, history.replaceState 可以通过pushState和replaceState接口操作浏览器历史,并且改变当前页面的URL。

下面附上一个简单的实例demo,仅供参考。

目录结构:

.
├── css
├── data
│   └── data.php
├── js
└── historyAjax.html

historyAjax.html

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	<button class="btn" id="btn1" data-page="news" data-url="/testPro/testDemo/news?page=news">button 1</button>
	<button class="btn" id="btn2" data-page="articals" data-url="/testPro/testDemo/artical?page=articals">button 2</button>
	<button class="btn" id="btn3" data-page="cars" data-url="/testPro/testDemo/cars?page=cars">button 3</button>
	<p id='txt'>首页</p>
</body>
<script src="js/jquery-2.2.2.min.js"></script>
<script src="js/history.js"></script>
</html>

history.js

$(function(){
	$('.btn').on('click',function(){
		var url = $(this).data('url');
		var page = $(this).data('page');
		var state = {
			url : url,
			page : page
		}
		history.pushState(state,null,url);
		$.ajax({
			url : './data/data.php',
			type : 'get',
			data : {page:page},
			success : function(res){
				$('#txt').html(res);
				state.contents = res;
				history.replaceState(state,null,url);
			}
		})
	});
	window.addEventListener('popstate', function(event) {
	  var state = history.state;
	  if(state == null){
		  console.log('null');
		  history.replaceState(null,null,'./historyAjax.html');
		  $('#txt').html('首页');
		  return;
	  }else{
		  console.log(state.page);
		  $('#txt').html(state.contents); // 直接从state中取内容,减少http请求
	  }

	});
});

data.php

<?php
	@$page = $_GET['page'];
	switch ($page) {
		case 'news':
			echo '这里是新闻页';
			break;
		case 'articals':
			echo '这里是文章页';
			break;
		case 'cars':
			echo '这里是汽车页';
			break;
		default :
			echo 'default';
	}
 ?>

更多相关文章: