pjax的介绍和DEMO

介绍

pjax其实就是window.history.pushState+window.history.replaceState+window.onpopstate+Ajax的技术应用。主要是解决页面局部刷新而浏览器地址栏随着改变的问题。同时也可以实现前进后退时只是局部更新的情况。

pushState(state,title,url)方法

向history对象中添加URL。 pushState()有三个参数:state对象是一个JSON对象(对应URL,唯一性),它关系到由pushState()方法创建出来的新的history实体;title(现在是被忽略,未作处理);URL(请求的链接)。

replaceState()方法

history.replaceState() 修改当前的URL,参数和pushState一样。

popstate事件

history实体被改变时,popstate事件将会发生。如果history实体是有pushState和replaceState方法产生的 popstate事件的state属性会包含一份来自history实体的state对象的拷贝。

注意细节

防止浏览器直接访问a[href]的链接,在onclick调用的方法中返回false;要想在前进后退时看到效果要重新加载链接,在popstate事件中添加请求。

例子(要在服务器中运行才能看到效果,可在Apache、Tomcat、Nginx等服务器中)

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<style type="text/css">
		.select{color:red;}
	</style>
	<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
	<script type="text/javascript">
		$(function(){

              $('.pjax').bind('click',function(){
              	$('.select').removeClass('select');
              	$(this).addClass('select');
              	$.ajax({
              		type:'GET',
              		url:this.href,
              		success:function(data){
              			$('#container').html(data);
              		}
              	});
              	window.history.pushState({url:this.href},null,this.href);
              	return false;
              });
              window.addEventListener("popstate", function() {
              	$.ajax({
              		type:'GET',
              		url:location.href,
              		success:function(data){
              			$('#container').html(data);
              		}
              	});										
	          });

		})
	</script>
</head>
<body>
<a href="pjax2.html" class="pjax">页面2</a>
<a href="pjax3.html" class="pjax">页面3</a>
<div id="container">页面1</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>
页面2
</body>
</html>
<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>
页面3
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值