We all know that ajax brings the ability to load asynchronously to the browser, improving the user experience in data verification, local refresh, etc., but at the same time there are the following problems:
1. You can change the page content without refresh, but you cannot change the page URL
2. The hash method cannot handle the browser's forward, backward and other problems
In order to solve the problems caused by traditional ajax, HTML5 strengthens the history API, adds pushState, replaceState interface and popstate events. I won’t introduce it in detail here. Students who do not have this knowledge recommend that you look at the relevant information first.
The pjax plugin encapsulates pushState and ajax operations, providing us with a simple method to develop such web applications. The specific steps are as follows:
Define containers that require local updates
<div id="container"></div>
Initialize pjax and listen to URL
The code copy 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 the pjax request by `$.pjax.reload('#container');`. According to the above logic, the following code can be written:
The code copy is as follows:
var pjaxFilter = function(req, res, next) {
if (req.get('X-PJAX')) {
next();
return;
}
//If it is not a pjax request, return to 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 rich APIs, please visit: jquery-pjax