Use Yii integrated pjax (pushstate + ajax) to load the page without refreshing, yiipjax

Source: Internet
Author: User
Tags html sample

Use Yii integrated pjax (pushstate + ajax) to load the page without refreshing, yiipjax

What is Pjax?

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

The BOM object history has been enhanced by a wave, mainly for operations on the history stack. Previously, only replace, go and so on will jump to and refresh the entire page. Now with pushState, replaceState and so on, simply operate on the history stack, but simply modify the content in the history stack, no side effects (the page will not jump to refresh)

PJAX Effect

You can use URLs to track the dynamic loading of ajax content. This technology is especially advantageous in the view of two step view layout. Without refreshing the new page, the response speed and user experience are greatly improved. When there are many static scripts and common modules, the overhead of reuse is minimized. For application examples, refer to the current google +, facebook, and the new Weibo version, which is also implemented based on the html5 pushState. Google plus has the most obvious performance. Click the navigation bar address, the arrow moves with the target, and the page loaded at the same time fades in, the effect is dazzling.

Dirty url and Clean url

Before pjax appears, the browser needs to support the window. location. hash attribute to implement a page without refreshing and tracking through URLs. Determine the url # address recorded after the anchor to determine the content to be loaded. The specific construction method is to write a hashchange monitoring function. When a hash change is triggered, the loaded content is determined. Its disadvantage is that earlier browsers such as ie6 do not support hash, and an iframe should be built to record the historical url for forward and backward implementation. The biggest problem is that # The post-generated content will not be indexed by search engines. google has provided a solution to encourage the use #! Direct the address to? In the request address of escape_fragment = url, I have seen or are using this hash bang on twitter, facebook, Renren, Sina Weibo, and Douban. Pass #! Because the general method is not easily indexed by search engines (such as Baidu in China), it is called dirty url, pjax can use the clean url to achieve the same effect and be compatible with various browsers. It is the most suitable method now.

Use PHP + jQuery to implement PJAX

You do not need to write a javascript plug-in based on pushState from the beginning, because jQuery has open-source projects and can be easily implemented. At present, I have already introduced it in the development project, and it is well compatible with the original version. Besides, I hope to let the audience see the promotion of the new version of Weibo. After I use it, it will look like this, this will happen after you use it.

Preparations before start:

1. jQuery libray

2. jQ-based pjax plug-in (github open source project)

3. PHP project code (for ease of sharing, this article uses the yii framework demonstration, which is similar in actual development)

I. Front-end implementation

It is easy to use, and the jquery-pjax plug-in is well encapsulated and can be customized according to your preferences (for example, copying the effect of g plus ), the following is a basic html sample code that integrates the above steps:

<? PhpYii: app ()-> clientScript-> registerCoreScript ('jquery '); Yii: app ()-> clientScript-> registerScriptFile (Yii: app () -> baseUrl. '/js/jquery-pjax/jquery. pjax. js '); // the actual location of your pjax storage prevails?> <Div id = "nav"> <a href = "<? Php echo Yii: app ()-> createUrl ('Article/Index');?> "> Article </a> </div> <div id =" main "> replaced content </div> <script type =" text/javascript ">$ (document). ready (function () {$ ("# main "). pjax ("a") ;}); </script>

The final purpose is to replace the text in the div whose id is main with the corresponding address content in the result returned by ajax when clicking the tag. The url is automatically updated and the page is not loaded again. The following describes the content to be processed at the backend.

Ii. PHP implementation

The php end mainly needs to handle two tasks: 1. Implement layout View layout 2. Determine pjax requests

Implementation in the Yii framework:

Perform the following processing on the action in the Controller (taking 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 diagram:

The following effect page is displayed after you click the article link or article link:


Notes for using jquery-pjax:

1. The returned template content cannot be plain text and must be wrapped in html tags.

2. For details about how to use the plug-in, refer to the github project instructions. The updated method may vary.

3. For earlier browsers that do not support pushstate, The pjax plug-in automatically determines and uses the traditional page loading mode.

4. When the pjax request time of a page exceeds the set time, refresh is used for loading. You need to adjust the relevant parameters in the plug-in.

The content of this article is completely described, and I hope it will be helpful for you to learn pjax (pushstate + ajax.

Related Article

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: 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.