当前位置: 移动技术网 > IT编程>开发语言>JavaScript > jQuery+pjax简单示例汇总

jQuery+pjax简单示例汇总

2018年05月20日  | 移动技术网IT编程  | 我要评论

pjax 是一个jquery插件,它使用 ajax 和 pushstate 来实现快速的浏览体验,包括真正的固定链接,页面标题和工作返回按钮。

ajax缺点是破坏了浏览器的前进后退,因为ajax的请求不会留在历史记录中。pjax就不一样了,pjax被解释成ajax+pushstate的封装,因为它把ajax的请求写入历史记录,并反映在地址栏,这样用户就能愉快地使用前进后退了。pjax有好几个实现方法,这里使用最常用的jquery库,使用jquery.pjax.js。演示代码的服务器端使用php脚本语言。

pjax用在那儿?就说百度云盘吧,这个大家肯定都用过。百度云盘pc端,在点击打开某个文件夹后会打开这个文件夹下的文件,其实显示文件的这个div就用到了pjax技术。地址栏变换,内容更换,但是却是一个ajax请求。等到后退的时候,不必重新请求上一层文件夹的内容,因为是存在在历史记录中的。而且,开发者还可以选择时候使用cache和storage缓存。

示例一、

<!doctype html>
<html>
<head>
 <title>pjax</title>
  <meta charset="utf-8">
</head>
<body>
 <h1>my site</h1>
 <div>
  go to <a href="res1.php" rel="external nofollow" >第一页</a>.<a href="res2.php" rel="external nofollow" >第二页</a>
 </div>
 <div id="container"></div>  
</body>
<script src="../jquery-2.1.4.min.js"></script>
<script src="../jquery.pjax.js"></script>
<script type="text/javascript">
$(document).pjax('a', '#container')
</script>
</html>

res1.php

<?php 
echo "<div style='background:red;'>第一页</div>";

res2.php

<?php 
echo "<div style='background:red;'>第二页</div>";

解释:

$(document).pjax('a', '#container') 其中 a 是触发元素, #container 是装载 pjax 返回内容的容器,下面也是这样。

示例二、

<!doctype html>
<html>
<head>
 <title>pjax</title>
  <meta charset="utf-8">
</head>
<body>
 <h1>my site</h1>
 <div>
  <input type="button" id="clickme" value="go">
 </div>
 <div id="container"></div>  
</body>
<script src="../jquery-2.1.4.min.js"></script>
<script src="../jquery.pjax.js"></script>
<script type="text/javascript">
$(function(){
  $('#clickme').click(function(){
    $.pjax({
      url: './res3.php',
      container: '#container'
    });
  });
});
</script>
</html>

服务器端代码:

res3.php:

<?php 
echo "<div style='background:red;'>第三页</div>";

三综合应用

window.history.pushstate(state, title, url);
// https://developer.mozilla.org/zh-cn/docs/web/api/history/pushstate
// @状态对象:  记录历史记录点的额外对象,可以为空.
// @页面标题:  目前所有浏览器都不支持.
// @可选的url: 浏览器不会检查url是否存在,只改变url.url必须同域,不能跨域.

pjax其实就是html5 window.history.pushstate(state, title, url)这个新的api加上传统的ajax技术,一般用来实现无刷新的页面加载.pushstate的作用主要是:改变url和添加返回历史.这样ajax无刷新加载页面后,用户还可以正常进行后退和前进,js的window.history.back()和window.history.forward()也能正常工作.下面就是一个用pushstate + jquery ajax实现的无刷新的页面加载,不支持的浏览器则自动退化成打开原始的链接打开形式.

index.php:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>index</title>
<script src="jquery.js"></script>
</head>
<body>
<div id="main">
  <a href="data.php" rel="external nofollow" >data.php</a>
  <script>
  $(document).ready(function() {
    $('#main').on('click','a',function(e) {
      if(window.history.pushstate) {
        e.preventdefault(); //不跟随原链接跳转
        url = $(this).attr('href');
        $.ajax({
          async: true,
          type: 'get',
          url: 'data.php',
          data: 'pjax=1',
          success: function(data) {
            window.history.pushstate(null, null, url); //改变url和添加返回历史
            document.title = data.title; //设置标题
            $('#main').html(data.main); //设置内容
          }
        });
      } else {
        return; //低版本ie8等不支持html5 pushstate,直接返回进行链接跳转
      }
    });
  });
  </script>
</div>
</body>
</html>

data.php:

<?php
if(isset($_get['pjax'])) {
  //pjax请求返回json
  $arr['title'] = 'data';
  $arr['main'] = '<h1>data content</h1>';
  //下面这两句是把php数组转成json对象返回
  header('content-type: application/json; charset=utf-8');
  echo json_encode($arr);
} else {
  //常规请求返回html
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>data</title>
<script src="jquery.js"></script>
</head>
<body>
<div id="main"><h1>data content</h1></div>
</body>
</html>
<?php } ?>

注意,js统计代码应该放到main块里面才能正常统计页面访问数.

示例二:

<div class="body"> 
  <?php $action_name = $think.action_name; ?> 
 
  <!-- 头部哟 --> 
  <?php if ($action_name == 'news'): ?> 
    <include file="brand:header_news" /> 
  <?php elseif ($action_name == 'forum'): ?> 
    <include file="brand:header_forum" /> 
  <?php endif; ?> 
 
  <!-- 资讯的二级分类 --> 
  <div class="cb"></div> 
  <div class="brand-news-nav pjax"> 
    <ul class="clearfix"> 
      <li <?php if($_get['cat'] == '') echo 'class="selected"'; ?>><a class="first" href="{:u("brand/$action_name")}">全部</a></li> 
      <volist name="cat_list" id="vo" key="i"> 
        <li <?php if($_get['cat'] == $vo['id']) echo 'class="selected"'; ?>><a href="{:u("brand/$action_name",array('cat'=>$vo['id']))}">{$vo.name}</a></li> 
      </volist> 
    </ul> 
  </div> 
 
  <script type="text/javascript"> 
    $(function(){ 
      $(document).pjax('.pjax a', '#pjax-container',{ 
        type:'post', 
        scrollto:false, 
      }); 
      $(document).on('pjax:click', function() { 
        enable_loading = false; 
      }) 
      $(document).on('pjax:send', function(){ 
        var str = "<p class='tc mt-10'>加载中...</p>"; 
        $('#pjax-container').html(str); 
      }) 
 
      //最后一个右侧加边框 
      $(".brand-news-nav ul li").last().children('a').addclass('last'); 
      $(".brand-news-nav ul li").click(function(){ 
        $(this).addclass('selected').siblings().removeclass('selected'); 
      }) 
    }) 
  </script> 
 
  <!-- 文章列表页 --> 
  <div class="wrap clearfix"> 
    <div class="brand-news-list fl" id="pjax-container"> 
      <include file="brand:article_pjax" /> 
    </div> 
    <div class="brand-news-right fr pb-20"> 
      <a href="{$adv3[0]['url']}"><img class="scrollloading" data-url="{$adv3[0]['images']|showimagepath}" src="__public__/index/images/loading270x160.gif" width="260" height="150"></a> 
      <p class="title mt-10">法律支持</p> 
      <ul class="bgc-fff"> 
        <volist name="law_list" id="vo"> 
          <a href="{:u('law',array('id'=>$vo['id']))}"><li>{$vo.name}</li></a> 
        </volist> 
      </ul> 
      <button class="btn btn-right mt-10 btn-consult">免费咨询</button> 
      <script type="text/javascript"> 
        $(function(){ 
          //最后一个需要添加一个last的样式 
          $(".brand-news-right li:last").addclass('last'); 
        }) 
      </script> 
    </div> 
  </div> 
</div> 

服务端代码

if(is_pjax()){ 
  $this->display('article_pjax'); 
}else{ 
  $this->display('article'); 
} 
//判断是否是pjax请求 
function is_pjax(){ 
  return array_key_exists('http_x_pjax', $_server) && $_server['http_x_pjax']; 
} 

其中的主要思想就是当.pjax a进行点击的时候,将#pjax-container的内容替换为请求后的内容。在后端处理时需要判断是否是pjax请求,如果是需要进行局部渲染,如果不是进行全部渲染。

因为pjax用到了html5技术,如果浏览器不支持html5那么网站会正常进行跳转式的加载,如果支持那么只是进行局部渲染(但是浏览器地址栏中的url会正常跟着a链接进行变动)。

注意上述的js代码中在配置pjax时有个参数scrollto:false,加上此参数表示点击连接后网页的scrollbar不会变动,如没有此参数,每次点击时浏览视窗会自动跳转到网页顶部

小结:pjax实际就是从服务器端返回一段代码片段,而不用刷新页面,并且同时对 url 地址进行修改,这样可以节省资源加载,提升页面加载速度。

附: pjax的github项目地址

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网