PushState implements no-refreshing Ajax page switching and pushstateajax
Preface
This is a common requirement: Click the page number to partially update the page (not to refresh the page as a whole), and generate historical management. Partial refresh is easy to implement. ajax can meet our needs, but it does not produce History Management. Fortunately, html5 provides us with several useful APIs to solve this problem. See the following.
Body
I. API
1. pushState
PushState () has three parameters: a State object, a title (ignored now), and an optional URL address.
State: the status information corresponding to the URL to jump.
Title: a null string (may be useful in the future ).
Url: the URL to jump to. It cannot be cross-origin.
Purpose:Add the current URL and history. state to history, and replace the current with the new state and URL. Does not cause page refresh.
2. replaceState
The history. replaceState () operation is similar to history. pushState (). The difference is that the replaceState () method modifies the current historical record entries rather than creating new ones.
3. window. onpopstate
History. go and history. back (including pressing the browser's forward and backward buttons), and The popstate event is triggered when the page is not refreshed (because history is modified by pushState, when an event occurs, the browser extracts the URL from history and replaces the current URL and history with the corresponding state object. state. You can also obtain history. state through event. state.
II. Implementation
The scenario is very simple. You can click the button to display different images and titles in the div, use ajax to refresh, and generate History Management.
<p class="page"> <a href="javascript:;">[ <span>1</span> ]</a> <a href="javascript:;">[ <span>2</span> ]</a> <a href="javascript:;">[ <span>3</span> ]</a> <a href="javascript:;">[ <span>4</span> ]</a></p><div> <p class="title"></p></div>
Core code
Function setUrl (page) {var url = location. pathname + '? Page = '+ page; history. pushState ({url: url}, '', url);} // Add an entry to the history record each time you click the button.
Note: during the first loading, you must replace the historical records for the first loading.
(Function () {// by default, the first page of var url = location. pathname + '? is displayed '? Page = 1'; // modify the current historical record history. replaceState ({url: url}, '', url );})()
Listen to the popstage event of the window, obtain the page number corresponding to the current history when the event occurs, and then execute ajax
window.addEventListener('popstate',function(){ var page = getPage(); xhr(page); })
This is the general skeleton.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.