JQuery + pjax simple example summary, jquerypjax Summary

Source: Internet
Author: User

JQuery + pjax simple example summary, jquerypjax Summary

Pjax is a jQuery plug-in that uses ajax and pushState for quick browsing, including real fixed links, page titles, and work return buttons.

The disadvantage of ajax is that it destroys the browser's forward and backward direction, because ajax requests will not stay in the history. Pjax is different. pjax is interpreted as an encapsulation of ajax + pushState because it writes ajax requests to historical records and reflects them in the address bar, in this way, the user can happily use and move forward and backward. Pjax has several implementation methods. Here we use the most common jQuery library and jquery. pjax. js. The server side of the Demo code uses the PHP script language.

Where is Pjax used? Let's talk about Baidu cloud disk. This is definitely used by everyone. On the PC side of Baidu cloud disk, after clicking to open a folder, the files in this folder will be opened. In fact, the div of the displayed file uses the pjax technology. The address bar is changed and the content is changed, but it is an ajax request. When you move back, you do not have to re-request the content of the previous folder because it exists in the history. In addition, developers can also choose to use cache and storage cache.

Example 1,

<! DOCTYPE html> 

Res1.php

<? Php echo "<div style = 'background: red; '> page 1 </div> ";

Res2.php

<? Php echo "<div style = 'background: red; '> page 2 </div> ";

Explanation:

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

Example 2,

<!DOCTYPE html>

Server code:

Res3.php:

<? Php echo "<div style = 'background: red; '> page 3 </div> ";

3. Comprehensive Application

Window. history. pushState (state, title, url );
// Https://developer.mozilla.org/zh-CN/docs/Web/API/History/pushState
// @ Status object: an additional object that records historical records. It can be blank.
// @ Page title: not supported by all browsers currently.
// @ Optional URL: the browser does not check whether the URL exists, but only changes the URL. URL must be in the same domain and cannot be cross-domain.

PJAX is actually an HTML5 window. history. the new API pushState (state, title, url), coupled with the traditional AJAX technology, is generally used to achieve refreshing page loading. pushState is mainly used to change the URL and add the return history. in this way, after AJAX does not refresh the page, the user can normally move back and forward, JS window. history. back () and window. history. forward () can also work normally. the following is a new page load without refreshing implemented by pushState + jQuery AJAX. Unsupported browsers will automatically degrade to open the original link opening form.

Index. php:

<! DOCTYPE html> 

Data. php:

<? Phpif (isset ($ _ GET ['pja']) {// The pjax request returns the JSON $ arr ['title'] = 'data '; $ arr ['main'] = '

Note: The JS Statistics Code should be placed in the main block to calculate the number of metrics on the page.

Example 2:

<Div class = "body"> <? Php $ action_name = $ Think. ACTION_NAME;?> <! -- Headers --> <? Php if ($ action_name = 'new'):?> <Include file = "Brand: header_news"/> <? Php elseif ($ action_name = 'Forum '):?> <Include file = "Brand: header_forum"/> <? Php endif;?> <! -- Secondary category of information --> <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 ")} "> all </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-iner', {type: 'post', scrollTo: false,}); $ (document ). on ('pjax: click', function () {enable_loading = false ;}) $ (document ). on ('pjax: send', function () {var str = "<p class = 'tc mt-10 '> loading... </p> "; $ ('# pjax-containe R'{.html (str) ;}) // Add the border to the right of the last one $ (". brand-news-nav ul li "). last (). children ('A '). addClass ('last'); $ (". brand-news-nav ul li "). click (function () {$ (this ). addClass ('selected '). siblings (). removeClass ('selected') ;}}) </script> <! -- Article list page --> <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']}">  </a> <p class =" title mt-10 "> legal support </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-right mt-10 btn-consult"> free consultation </button> <script type = "text/javascript" >$ (function () {// Add a last style $ (". brand-news-right li: last "). addClass ('last') ;}) </script> </div>

Server code

if(is_pjax()){   $this->display('article_pjax'); }else{   $this->display('article'); } 
// Determine whether the request function is_pjax () {return array_key_exists ('HTTP _ X_PJAX ', $ _ SERVER) & $ _ SERVER ['HTTP _ X_PJAX'];}

The main idea is to replace the content of # pjax-container with the content after the request when. pjax a clicks. During backend processing, you must determine whether the request is a pjax request. If local rendering is required, if not all rendering is required.

Because pjax uses the HTML5 technology, if the browser does not support Html5, the website will normally perform jump loading, if yes, only partial rendering is supported (but the url in the address bar of the browser changes normally with the link ).

Note that the preceding js Code has a scrollTo: false parameter when pjax is configured. Adding this parameter indicates that the scrollBar of the webpage will not change after the connection is clicked. If this parameter is not set, the browser window automatically jumps to the top of the page each time you click

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

Appendix: github Project address https://github.com/defunkt/jquery-pjax for pjax

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.