The hash property is a readable and writable string that is the anchor part of the URL (the part starting with the # number).
grammar
location.hash
In our project, there are a large number of pages with ajax query form + result list. Since the query result is returned by ajax, when the user clicks an item in the list and enters the details page, he clicks the browser back button to return to the ajax query page. At this time, everyone knows that the form and results of the query page have returned to the default state.
If you have to re-enter the query criteria every time you return to the page, or if you have to go to the page of the list, then users will really go crazy with this experience.
In our project, we wrote a very simple JavaScript base class to process location.hash and save the page status. Today I will share it with you.
(The content of this article may be a bit difficult for beginners in JavaScript, because it involves JS object-oriented knowledge, such as defining classes, inheritance, virtual methods, reflection, etc.)
Let's take a look at our needs first
Our project is a WeChat-based H5 task management system. The page prototype to be completed is shown in the figure below:
The requirements should be very clear, that is, click on the query form, use ajax to return the query results, and then click on a task in the list to enter the task details page. Since administrators (project managers) usually handle multiple tasks at once, they will constantly switch between the task details page and the query list page. If pressing the return key at this time cannot save the status of the query page, then you have to re-enter the query conditions every time you return to the query page. This experience is definitely unbearable.
Therefore, we need to find a way to save the page status so that when the user presses the fallback key, the query conditions and results are still there.
Solution
There are many ideas for saving page status, but we think using location.hash should be the best way.
The idea is as follows:
1. After the user enters the query conditions and clicks OK, we serialize the query conditions into a string, and add the query conditions to the url through "#" to get a new url, and then call location.replace (new url) to modify the address in the browser address bar.
2. When the user presses the fallback key to fall back to the query page, it can also be said that when the page is loading, deserialize location.hash into query conditions, and then update the query conditions to the query form and execute the query.
The idea is very simple. The key point is the location.replace method. This method is not only to modify the URL of the address bar in the browser, but more importantly, it will replace the record of the current page in window.history. If the location.replace method is not used, each fallback will fall back to the previous query condition. Of course, such requirements may also be useful for certain projects.
Final solution
If this article only shares the above solution ideas, it will be of little value. The value of this article should be the simple but very powerful JavaScript class we wrote.
If you understand the above solution, then take a look at this simple JavaScript class:
(function() {if (window.HashQuery) {return;}window.HashQuery = function() {};HashQuery.prototype = {parseFromLocation: function() {if (location.hash === '' || location.hash.length === ) {return;}var properties = location.hash.substr().split('|');var index = ;for (var p in this) {if (!this.hasOwnProperty(p) || typeof this[p] != 'string') {continue;}if (index < properties.length) {this[p] = properties[index];if (this[p] === '-') {this[p] = '';}}index++;}},updateLocation: function() {var properties = [];for (var p in this) {if (!this.hasOwnProperty(p) || typeof this[p] != 'string') {continue;}var value = this[p];properties.push(value === '' ? '-' : value);}var url = location.origin + location.pathname + location.search + "#" + properties.join('|');location.replace(url);}};})();There are only 2 methods in this class. The HashQuery.parseFromLocation() method deserializes from location.hash to an instance of the HashQuery subclass. The HashQuery.updateLocation() method serializes and updates the instance of the current HashQuery subclass to window.location.
You can see that the HashQuery class has no properties, because we only define a base class, and the properties of the class are defined in the subclass. This is also realistic, because the query conditions can only be known on the specific page.
Also, note the serialization and deserialization here. The serialization here is just to use the JavaScript reflection mechanism to separate the values of all string attributes (in order) of the instance with "|"; while serialization is to separate the strings with "|", and then update the properties of the instance with reflection (in order).
How to use HashQuery class
It's very simple to use.
The first step is to define a subclass and add all the query conditions needed to be used to the string attributes, such as our code:
(function() {window.TaskSearchHashQuery = function () {HashQuery.constructor.call(this);this.iterationId = '';this.assignedUserId = '';this.status = '';this.keyword = '';};TaskSearchHashQuery.constructor = TaskSearchHashQuery;TaskSearchHashQuery.prototype = new HashQuery();})();In the second step, call the HashQuery.parseFromLocation() and HashQuery.updateLocation() methods on the query page. The following code is our complete query page:
(function() {var urls = {list: "/app/task/list"};var hashQuery = null;var pager = null;$(document).ready(function() {hashQuery = new TaskSearchHashQuery();hashQuery.parseFromLocation();//Called here, deserialize objectupdateFormByHashQuery();$("#btnSearch").click(function() {updateHashQueryByForm();hashQuery.updateLocation();//Called here, serialize the query conditions and update it to location.hash$("#lblCount").html("Loading...");pager.reload();page.hideSearch();});pager = new ListPager("#listTasks", urls.list);pager.getPostData = function(index) {return "pageIndex=" + index + "&pageSize=" + "&projectId=" + page.projectId+ "&iterationId=" + hashQuery.iterationId+ "&assignedUserId=" + hashQuery.assignedUserId+ "&status=" + hashQuery.status+ "&keyword=" + hashQuery.keyword;};pager.onLoaded = function() {$("#lblCount").html("Total" + $("#hfPagerTotalCount").val() + "Tasks");$("#hfPagerTotalCount").remove();};pager.init();});function updateHashQueryByForm() {hashQuery.iterationId = $("#ddlIterations").val();hashQuery.assignedUserId = $("#ddlUsers").val();hashQuery.status = $("#ddlStatuses").val();hashQuery.keyword = $("#txtKeyword").val();};function updateFormByHashQuery() {$("#ddlIterations").val(hashQuery.iterationId);$("#ddlUsers").val(hashQuery.assignedUserId);$("#ddlStatuses").val(hashQuery.status);$("#txtKeyword").val(hashQuery.keyword);};})();Summarize
This is all we know about using location.hash in our project to save page status. I wonder how you deal with such needs in your WEB project?
The above content is the tips for saving page status of the location.hash that the editor introduced to you. I hope it will be helpful to everyone!