Pjax = pushState + ajax
Because this is a common component, I have written it into the Middleware of slim (if you do not know what the middleware is or how to write it, you can check it here)
The general principle is that after the slim framework is rendered and output, analyze the dom structure, extract the part required by pjax, and then return the content as the response to the browser's ajax request.
Preview: click the tab to view the effect.
| The code is as follows: |
Copy code |
$ App-> add (new \ Support \ PjaxMiddleware ()); <? Php Namespace Support; Use Slim \ Middleware; Use Slim \ Http \ Request; Use Slim \ Http \ Response; Use Symfony \ Component \ DomCrawler \ Crawler; Class PjaxMiddleware extends Middleware { Public function call () { $ Request = $ this-> app-> request (); $ Response = $ this-> app-> response (); $ This-> next-> call (); If (! $ Request-> headers ('x-PJAX ') | $ response-> isRedirect ()){ Return; } $ This-> filterResponse ($ response, $ request-> headers ('x-PJAX-CONTAINER ')-> setUriHeader ($ response, $ request ); } Private function filterResponse (Response $ response, $ container) { $ Crawler = new Crawler ($ response-> getBody ()); $ Response-> setBody ($ this-> makeTitle ($ crawler). $ this-> fetchContents ($ crawler, $ container )); Return $ this; } Private function makeTitle (Crawler $ crawler) { $ Title = $ crawler-> filter ('head> title')-> html (); Return "<title >{$ title} </title> "; } Private function fetchContents (Crawler $ crawler, $ container) { $ Content = $ crawler-> filter ($ container ); If (! $ Content-> count ()){ $ This-> app-> stop (); } Return $ content-> html (); } Private function setUriHeader (Response $ response, Request $ request) { $ Query = $ request-> get (); Unset ($ query ['_ pjax']); $ Response-> header ('x-PJAX-URL ', $ request-> getResourceUri ().'? '. Http_build_query ($ query )); } } |