pjax

pjax是对ajax + pushState的封装,可以很方便的使用pushState技术

点击一个站内的链接的时候, 不是做页面跳转, 而是只是站内页面刷新,刷新页面的同时, 浏览器地址栏位上面的地址也是会更改, 用浏览器的回退功能也能够回退到上一个页面。

好处:

1、用户体验提升

2、减少带宽消耗和服务器消耗

....

官方文档:

https://github.com/defunkt/jquery-pjax

Demo(要在服务器中运行才能看到效果)

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

pjax1.html

<!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>

pjax2.html

<!DOCTYPE html>

<html>

<head>

<title></title>

</head>

<body>

页面2

</body>

</html>

pjax3.html

<!DOCTYPE html>

<html>

<head>

<title></title>

</head>

<body>

页面3

</body>

</html>

猜你喜欢

转载自tzhennan.iteye.com/blog/2418483