Home Web Front-end JS Tutorial Use Yii integrated pjax (pushstate+ajax) to load the page without refreshing

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

May 24, 2018 pm 05:29 PM
pjax accomplish

This article will introduce Yii to integrate pjax (pushstate ajax) to achieve non-refresh loading of pages. Let’s learn together

What is Pjax?

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

The BOM object history has been enhanced, mainly for operations on the history stack. In the past, only replace, go and the like would jump. Turn and refresh the entire page. Now there are pushState, replaceState and other methods that simply operate the history stack. They just modify the content in the history stack and have no side effects (the page will not jump and refresh)

PJAX Effect

The dynamically loaded content of ajax can be tracked through the url. This technique is particularly beneficial in views with two step view layouts. Loading the page without refreshing means that the response speed and user experience have been greatly improved. When there are many static scripts and common modules, the cost of reuse is saved to the greatest extent. Application examples can refer to current Google, Facebook and the new version of Weibo, which are also implemented based on HTML5 pushState. The performance of Google Plus is the most obvious. Click the navigation bar address, 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 advent of pjax, in order to load the page without refreshing and track it through the url, the browser needed to support window.location.hash Attributes. The content that needs to be loaded is determined by judging the address recorded after the url# anchor. The specific construction method is to write a hashchange monitoring function, and when the hash change is triggered, the content to be loaded is judged. Its disadvantage is that lower version browsers such as ie6 do not support hash, and an additional iframe needs to be built to record historical URLs to achieve forward and backward. The biggest problem is that the content generated after # will not be indexed by search engines. Google has provided a solution before, advocating the use of #! to guide the address to a request address of ?escape_fragment=url. I use twitter, facebook, Everyone on Renren, Sina Weibo and the closed Douban have seen that this kind of hash bang has been or is being used. pass#! To realize the url loaded without refreshing, 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 is well compatible with various This browser is the most suitable method now

Use PHP jQuery to implement PJAX

There is no need to write a javascript plug-in based on pushState from scratch, because jQuery already has a project to implement it It is open source and can be easily implemented. At present, I have introduced it into the project under development, and it is very compatible with the original one. Not to mention the promotion of the new version of Weibo. I hope that the audience can see that this is what I look like after using it, and you will also see it after using it. It looks like this

Preparation before starting:

1. jQuery libray

2. jQ-based pjax plug-in (open source project on github) https://github. com/defunkt/jquery-pjax

3. PHP project code (for easy sharing, this article uses the yii framework for demonstration, and the actual development is similar)

1. Front-end implementation

It is really easy to use, and the jquery-pjax plug-in is well packaged. It can definitely be customized according to your preferences (such as copying the effect of g plus). The following is a basic html sample code that integrates the above steps:

<?php
Yii::app()->clientScript->registerCoreScript(&#39;jquery&#39;);
Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl . &#39;/js/jquery-pjax/jquery.pjax.js&#39;);//具体以你存放pjax的实际位置为准
?>
<p id="nav">
  <a href="<?php echo Yii::app()->createUrl(&#39;article/index&#39;);?>">article</a>
</p>
<p id="main">替换的内容</p>
<script type="text/javascript">
  $(document).ready(function(){
    $("#main").pjax("a");
  });
</script>
Copy after login

The ultimate goal is to replace the text in p with the id of main with the corresponding address content and url through the results returned by ajax when clicking the a tag. Updates automatically and the page does not reload. Let's start to implement the content to be processed by the backend

2. Implementation of the PHP side

The tasks that the PHP side needs to handle are mainly two: 1. Implement the layout view layout 2 .Judge the request coming from pjax

Implementation in Yii framework:

Do the following processing of action in the controller (take the index of Article as an example):

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

Effect demonstration picture:

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

----------------------------------------

Things to note when using jquery-pjax:

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

2. Plug-in How to use, please refer to the project description on github for details. The usage may be different after updating.

3. For lower version browsers that do not support pushstate, the pjax plug-in will automatically determine and use the traditional page loading mode

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

The above is what I compiled for everyone. I hope it will be useful to everyone in the future. helpful.

Related articles:

Jquery and PHP combined to implement AJAX long polling

Js ajax progress bar code when loading

Initial understanding of JavaScript, Ajax, jQuery, and comparison of the relationship between the three

The above is the detailed content of Use Yii integrated pjax (pushstate+ajax) to load the page without refreshing. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement dual WeChat login on Huawei mobile phones? How to implement dual WeChat login on Huawei mobile phones? Mar 24, 2024 am 11:27 AM

How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

Use Java to write code to implement love animation Use Java to write code to implement love animation Dec 23, 2023 pm 12:09 PM

Realizing love animation effects through Java code In the field of programming, animation effects are very common and popular. Various animation effects can be achieved through Java code, one of which is the heart animation effect. This article will introduce how to use Java code to achieve this effect and give specific code examples. The key to realizing the heart animation effect is to draw the heart-shaped pattern and achieve the animation effect by changing the position and color of the heart shape. Here is the code for a simple example: importjavax.swing.

PHP Programming Guide: Methods to Implement Fibonacci Sequence PHP Programming Guide: Methods to Implement Fibonacci Sequence Mar 20, 2024 pm 04:54 PM

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence

How to implement the WeChat clone function on Huawei mobile phones How to implement the WeChat clone function on Huawei mobile phones Mar 24, 2024 pm 06:03 PM

How to implement the WeChat clone function on Huawei mobile phones With the popularity of social software and people's increasing emphasis on privacy and security, the WeChat clone function has gradually become the focus of people's attention. The WeChat clone function can help users log in to multiple WeChat accounts on the same mobile phone at the same time, making it easier to manage and use. It is not difficult to implement the WeChat clone function on Huawei mobile phones. You only need to follow the following steps. Step 1: Make sure that the mobile phone system version and WeChat version meet the requirements. First, make sure that your Huawei mobile phone system version has been updated to the latest version, as well as the WeChat App.

Development suggestions: How to use the ThinkPHP framework to implement asynchronous tasks Development suggestions: How to use the ThinkPHP framework to implement asynchronous tasks Nov 22, 2023 pm 12:01 PM

"Development Suggestions: How to Use the ThinkPHP Framework to Implement Asynchronous Tasks" With the rapid development of Internet technology, Web applications have increasingly higher requirements for handling a large number of concurrent requests and complex business logic. In order to improve system performance and user experience, developers often consider using asynchronous tasks to perform some time-consuming operations, such as sending emails, processing file uploads, generating reports, etc. In the field of PHP, the ThinkPHP framework, as a popular development framework, provides some convenient ways to implement asynchronous tasks.

Master how Golang enables game development possibilities Master how Golang enables game development possibilities Mar 16, 2024 pm 12:57 PM

In today's software development field, Golang (Go language), as an efficient, concise and highly concurrency programming language, is increasingly favored by developers. Its rich standard library and efficient concurrency features make it a high-profile choice in the field of game development. This article will explore how to use Golang for game development and demonstrate its powerful possibilities through specific code examples. 1. Golang’s advantages in game development. As a statically typed language, Golang is used in building large-scale game systems.

How to implement exact division operation in Golang How to implement exact division operation in Golang Feb 20, 2024 pm 10:51 PM

Implementing exact division operations in Golang is a common need, especially in scenarios involving financial calculations or other scenarios that require high-precision calculations. Golang's built-in division operator "/" is calculated for floating point numbers, and sometimes there is a problem of precision loss. In order to solve this problem, we can use third-party libraries or custom functions to implement exact division operations. A common approach is to use the Rat type from the math/big package, which provides a representation of fractions and can be used to implement exact division operations.

PHP Game Requirements Implementation Guide PHP Game Requirements Implementation Guide Mar 11, 2024 am 08:45 AM

PHP Game Requirements Implementation Guide With the popularity and development of the Internet, the web game market is becoming more and more popular. Many developers hope to use the PHP language to develop their own web games, and implementing game requirements is a key step. This article will introduce how to use PHP language to implement common game requirements and provide specific code examples. 1. Create game characters In web games, game characters are a very important element. We need to define the attributes of the game character, such as name, level, experience value, etc., and provide methods to operate these

See all articles