介绍
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>