Home  >  Article  >  Web Front-end  >  Use pjax to change the page url without refreshing_javascript tips

Use pjax to change the page url without refreshing_javascript tips

WBOY
WBOYOriginal
2016-05-16 16:15:581591browse

We all know that ajax brings asynchronous loading capabilities to browsers, which improves user experience in terms of data verification, partial refresh, etc., but at the same time, there are the following problems:

1. The page content can be changed without refreshing, but the page URL cannot be changed
2. The hash method cannot handle browser forward and backward issues well

In order to solve the problems caused by traditional ajax, the history API has been strengthened in HTML5, adding pushState, replaceState interfaces and popstate events. I will not introduce it in detail here. Students who do not have this knowledge are recommended to read the relevant information first.

The pjax plug-in encapsulates pushState and ajax operations, providing us with a simple method to develop this type of web application. The specific steps are as follows:

Define containers that require partial updates


Initialize pjax and listen to URL

Copy code The code is as follows:

$(function(){
// pjax
$(document).pjax('a', '#container');
$.pjax.reload('#container');
})

Backend handles pjax requests

The processing logic of the backend is to first determine whether it is a pjax request. If so, return the local content according to the request parameters, otherwise return the layout layout, and then initiate pjax by `$.pjax.reload('#container');` ask. Based on the above logic, the following code can be written:

Copy code The code is as follows:

var pjaxFilter = function(req, res, next) {
if (req.get('X-PJAX')) {
next();
return;
}
//If it is not a pjax request, return the layout template directly
res.render('layout', { title: 'Pjax simple demo' });
};
router.get('/', pjaxFilter, function(req, res) {
res.render('index');
});
router.get('/poem/:id', pjaxFilter, function(req, res) {
var poemId = req.params.id;
res.render('poem/' poemId);
})

Full code: pjax-demo

This is just the most basic function of pjax. pjax provides a rich API, please visit: jquery-pjax

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