Home > Web Front-end > JS Tutorial > body text

jQuery pjax simple example summary

小云云
Release: 2018-01-17 14:04:22
Original
2121 people have browsed it

pjax is a jQuery plugin that uses ajax and pushState to achieve a fast browsing experience, including real permalinks, page titles, and working back buttons. This article mainly shares with you a summary of jQuery pjax simple examples, hoping to help everyone.

The disadvantage of ajax is that it destroys the browser's forward and backward movement, because ajax requests will not stay in the history. Pjax is different. Pjax is interpreted as a package of ajax+pushState, because it writes ajax requests into the history and reflects them in the address bar, so that users can happily use forward and backward. There are several implementation methods for pjax. The most commonly used jQuery library is used here, using jquery.pjax.js. The server side of the demo code uses the PHP scripting language.

Where is Pjax used? Let’s talk about Baidu Cloud Disk, everyone must have used this. On the PC side of Baidu Cloud Disk, when you click to open a folder, the file in the folder will be opened. In fact, the p that displays the file uses pjax technology. The address bar changes and the content changes, but it is an ajax request. When you go back, you don't have to re-request the contents of the upper-level folder because it exists in the history. Moreover, developers can also choose to use cache and storage caching.

Example 1,


<!DOCTYPE html>
<html>
<head>
 <title>pjax</title>
  <meta charset="utf-8">
</head>
<body>
 <h1>My Site</h1>
 <p>
  Go to <a href="res1.php" rel="external nofollow" >第一页</a>.<a href="res2.php" rel="external nofollow" >第二页</a>
 </p>
 <p id="container"></p>  
</body>
<script src="../jquery-2.1.4.min.js"></script>
<script src="../jquery.pjax.js"></script>
<script type="text/javascript">
$(document).pjax(&#39;a&#39;, &#39;#container&#39;)
</script>
</html>
Copy after login

res1.php


<?php 
echo "<p style=&#39;background:red;&#39;>第一页</p>";
Copy after login

res2.php


<?php 
echo "<p style=&#39;background:red;&#39;>第二页</p>";
Copy after login

Explanation:

$(document).pjax('a', '#Container') where a is the trigger element, # container is the container that loads the content returned by pjax, and the same is true below.

Example 2,


<!DOCTYPE html>
<html>
<head>
 <title>pjax</title>
  <meta charset="utf-8">
</head>
<body>
 <h1>My Site</h1>
 <p>
  <input type="button" id="clickMe" value="GO">
 </p>
 <p id="container"></p>  
</body>
<script src="../jquery-2.1.4.min.js"></script>
<script src="../jquery.pjax.js"></script>
<script type="text/javascript">
$(function(){
  $(&#39;#clickMe&#39;).click(function(){
    $.pjax({
      url: &#39;./res3.php&#39;,
      container: &#39;#container&#39;
    });
  });
});
</script>
</html>
Copy after login

Server-side code:

res3.php:


<?php 
echo "<p style=&#39;background:red;&#39;>第三页</p>";
Copy after login

Three comprehensive applications

window.history.pushState(state, title, url);
// https://developer.mozilla.org/zh- CN/docs/Web/API/History/pushState
// @State object: Additional object that records historical points, can be empty.
// @Page title: Currently not supported by all browsers.
// @Optional URL: The browser will not check whether the URL exists, only change the URL. The URL must be in the same domain and cannot cross domains.

PJAX is actually HTML5 window.history.pushState (state, title, url) This new API plus traditional AJAX technology is generally used to achieve page loading without refreshing. The main function of pushState is to change the URL and add return history. In this way, after AJAX loads the page without refreshing, the user You can also go back and forward normally, and JS's window.history.back() and window.history.forward() can also work normally. The following is a page loading without refreshing using pushState + jQuery AJAX. Browsing is not supported. The server will automatically degrade to the original link opening form.

index.php:


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

data.php:


<?php
if(isset($_GET[&#39;pjax&#39;])) {
  //PJAX请求返回JSON
  $arr[&#39;title&#39;] = &#39;Data&#39;;
  $arr[&#39;main&#39;] = &#39;<h1>Data Content</h1>&#39;;
  //下面这两句是把PHP数组转成JSON对象返回
  header(&#39;Content-Type: application/json; charset=utf-8&#39;);
  echo json_encode($arr);
} else {
  //常规请求返回HTML
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Data</title>
<script src="jquery.js"></script>
</head>
<body>
<p id="main"><h1>Data Content</h1></p>
</body>
</html>
<?php } ?>
Copy after login

Note that the JS statistics code should be placed in the main block to properly count the number of page visits.

Example 2:


<p class="body"> 
  <?php $action_name = $Think.ACTION_NAME; ?> 
 
  <!-- 头部哟 --> 
  <?php if ($action_name == &#39;news&#39;): ?> 
    <include file="Brand:header_news" /> 
  <?php elseif ($action_name == &#39;forum&#39;): ?> 
    <include file="Brand:header_forum" /> 
  <?php endif; ?> 
 
  <!-- 资讯的二级分类 --> 
  <p class="cb"></p> 
  <p class="brand-news-nav pjax"> 
    <ul class="clearfix"> 
      <li <?php if($_GET[&#39;cat&#39;] == &#39;&#39;) echo &#39;class="selected"&#39;; ?>><a class="first" href="{:U("Brand/$action_name")}">全部</a></li> 
      <volist name="cat_list" id="vo" key="i"> 
        <li <?php if($_GET[&#39;cat&#39;] == $vo[&#39;id&#39;]) echo &#39;class="selected"&#39;; ?>><a href="{:U("Brand/$action_name",array(&#39;cat&#39;=>$vo[&#39;id&#39;]))}">{$vo.name}</a></li> 
      </volist> 
    </ul> 
  </p> 
 
  <script type="text/javascript"> 
    $(function(){ 
      $(document).pjax(&#39;.pjax a&#39;, &#39;#pjax-container&#39;,{ 
        type:&#39;post&#39;, 
        scrollTo:false, 
      }); 
      $(document).on(&#39;pjax:click&#39;, function() { 
        enable_loading = false; 
      }) 
      $(document).on(&#39;pjax:send&#39;, function(){ 
        var str = "<p class=&#39;tc mt-10&#39;>加载中...</p>"; 
        $(&#39;#pjax-container&#39;).html(str); 
      }) 
 
      //最后一个右侧加边框 
      $(".brand-news-nav ul li").last().children(&#39;a&#39;).addClass(&#39;last&#39;); 
      $(".brand-news-nav ul li").click(function(){ 
        $(this).addClass(&#39;selected&#39;).siblings().removeClass(&#39;selected&#39;); 
      }) 
    }) 
  </script> 
 
  <!-- 文章列表页 --> 
  <p class="wrap clearfix"> 
    <p class="brand-news-list fl" id="pjax-container"> 
      <include file="Brand:article_pjax" /> 
    </p> 
    <p class="brand-news-right fr pb-20"> 
      <a href="{$adv3[0][&#39;url&#39;]}"><img class="scrollLoading" data-url="{$adv3[0][&#39;images&#39;]|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(&#39;law&#39;,array(&#39;id&#39;=>$vo[&#39;id&#39;]))}"><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(&#39;last&#39;); 
        }) 
      </script> 
    </p> 
  </p> 
</p>
Copy after login

Server-side code


if(is_pjax()){ 
  $this->display(&#39;article_pjax&#39;); 
}else{ 
  $this->display(&#39;article&#39;); 
}
Copy after login


//判断是否是pjax请求 
function is_pjax(){ 
  return array_key_exists(&#39;HTTP_X_PJAX&#39;, $_SERVER) && $_SERVER[&#39;HTTP_X_PJAX&#39;]; 
}
Copy after login

The main idea is that when .pjax a is clicked, #pjax-container The content is replaced with the requested content. During back-end processing, it is necessary to determine whether it is a pjax request. If it is a partial rendering, if not all rendering is required.

Because pjax uses HTML5 technology, if the browser does not support Html5, the website will jump load normally. If it supports it, it will only perform partial rendering (but the url in the browser address bar will Normally follow the a link to make changes).

Note that in the above js code, there is a parameter scrollTo:false when configuring pjax. Adding this parameter means that the scrollBar of the web page will not change after clicking the connection. Without this parameter, every time you click The browsing window will automatically jump to the top of the web page

Summary: Pjax actually returns a code snippet from the server without refreshing the page, and at the same time modifies the url address, which can save resource loading and improve page loading. speed.

Attachment: pjax’s github project addresshttps://github.com/defunkt/jquery-pjax

Related recommendations:

What is Pjax

Using Pjax in Laravel 5.1

Navigation bar PJAX refresh problem

The above is the detailed content of jQuery pjax simple example summary. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!