Using pjax (pushstate + Ajax) integrated by Yii to load pages without refreshing


What is pjax?

Pjax = history.pushState + Ajax
   = history.pushState + Async JS + XML(xhr?)

BOM object history has been enhanced a wave, mainly for the operation of history stack. In the past, only replace, go and the like would jump and refresh the whole page. Now there are pushstate, replacestate and other methods to simply operate history stack, which only modify the contents of history stack, without side effects (the page will not jump and refresh)

Pjax effect

The dynamic loading content of Ajax can be tracked through URL. This technique has great advantages especially in the two step view layout. Loading pages without refreshing means that the response speed and user experience have been greatly improved. In the case of more static scripts and general modules, the overhead of reusing part has been saved to the greatest extent. Application examples can refer to the current Google +, Facebook and the new version of Weibo, which are also implemented in pushstate based on HTML5. The performance of Google plus is the most obvious. Click the address of the navigation bar, the arrow moves with the target, and the loaded page fades in at the same time. The effect is very dazzling.

Dirty URL and clean URL

Before the appearance of pjax, browser support is needed to realize the page loading without refresh and tracking through URL window.location.hash Property. The specific construction method is to write a hashchange monitoring function to determine the content to be loaded when the hash changes. The disadvantage of this method is that for lower version browsers, such as IE6, hash is not supported, so it is necessary to build another iframe to record the history URL and realize forward and backward. The biggest problem is that the content generated after # will not be indexed by the search engine. Google has provided a solution before, advocating #! To guide the address to an? Escape_ In the request address of fragment = URL, I have seen or are using this hash bang in twitter, Facebook, Renren, Sina Weibo and Douban, which has been closed. Through! Because the general method is not easy to be included by search engines (such as domestic Baidu), it is called dirty URL. Relatively speaking, pjax can use clean URL to get the same effect, and can be well compatible with all kinds of browsers. It is the most suitable method now

Using PHP + jQuery to realize pjax

There is no need to write a JavaScript plug-in based on pushstate from scratch, because jQuery has been open source and can be easily implemented. At present, I have introduced it into the project under development, and it is well compatible with the original one. Besides, the promotion of the new version of microblog, I hope to let the audience see that it will look like this after I use it up, and it will look like this after you use it up

Preparation before starting:

1. jQuery libray

2. Pjax plug-in based on JQ (open source project on GitHub)

3. PHP project code (easy to share, this paper uses Yii framework demonstration, the actual development is similar)

1、 Front end implementation

It’s easy to use, and jQuery pjax plug-in is well packaged. It can be customized according to your preference (such as copying the effect of G plus). Here’s a basic HTML sample code integrating the above steps:

Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl . '/js/jquery-pjax/ jquery.pjax.js '; // the actual location where you store the pjax will prevail
  <a href="<?php echo Yii::app()->createUrl('article/index');?>">article</a>
< div > replaced content < / div >
<script type="text/javascript">

The ultimate goal is to replace the text in the div with ID main with the corresponding address content through the result returned by Ajax when clicking the a tag. The URL will be updated automatically, and the page will not be reloaded. Now we start to implement the content to be processed by the back end

2、 Implementation of PHP client

There are two main tasks that PHP needs to deal with: 1. Implement the layout view layout; 2. Judge the request from pjax

Implementation in Yii framework:

In the controller, the action is processed as follows (take the index of article as an example)

public function actionIndex() {
  $this->layout = '//layouts/column1';
  $dataProvider = new CActiveDataProvider('Article', array(
    'criteria' => array('order' => 'create_time DESC')
  if (array_key_exists('HTTP_X_PJAX', $_SERVER) && $_SERVER['HTTP_X_PJAX']) {
    $this->renderPartial('index', array(
       'dataProvider' => $dataProvider,
  } else {
    $this->render('index', array(
      'dataProvider' => $dataProvider,

Effect demonstration picture:

After clicking the article link or article link, the following effect page will appear:


Notes in using jQuery pjax:

1. The returned template content cannot be plain text and needs to be wrapped with HTML tags

2. For the usage of the plug-in, please refer to the project description of GitHub for details. The usage may be different after the update

3. For low version browsers that don’t support pushstate, pjax plug-in will automatically judge and use the traditional page loading mode

4. When the pjax request time of a page exceeds the set time, refresh will be used to load, and the relevant parameters in the plug-in need to be adjusted

I hope it will be helpful for you to learn pjax (pushstate + Ajax).