Home > Web Front-end > JS Tutorial > body text

Location.hash techniques for saving page status_javascript techniques

WBOY
Release: 2016-05-16 15:03:20
Original
1245 people have browsed it

The hash attribute is a readable and writable string that is the anchor part of the URL (the part starting from the # sign).

Grammar

location.hash

In our project, there are a large number of ajax query form + result list pages. Since the query results are returned by ajax, when the user clicks an item in the list to enter the details page, then clicks the browser back button to return to 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 conditions every time you return to the page, or even have to go to a certain page in the list, then users will really go crazy with this experience.

In our project, we wrote a very simple JavaScript base class to handle location.hash to save the page state. I will share it with you today.

(The content of this article may be a bit difficult for JavaScript beginners 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 an H5 task management system based on WeChat. The prototype of the page to be completed is as shown 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 one time, they will constantly switch between the task details page and the query list page. At this time, if the query page status cannot be saved by pressing the return key, it will be necessary to return to the query page every time. The experience of re-entering the query conditions is definitely intolerable.

So, we need to find a way to save the page status so that when the user presses the back button, the query conditions and results are still there.

Solution ideas

There are many ideas for saving page status, but we think using location.hash should be the best method.

The idea is as follows:

1. After the user enters the query conditions and clicks OK, we serialize the query conditions into a string, add the query conditions to the end of 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 back button to return to the query page, which can also be said to be when the page is loaded, deserialize location.hash into query conditions, 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 not only modifies the URL of the address bar in the browser, but more importantly, replaces the record of the current page in window.history. If the location.replace method is not used, each rollback will fall back to the previous query condition. Of course, such a requirement may be useful for some projects.

Final Solution

If this article only shares the above solution ideas, it will not be of much value. The value of this article should be the simple but 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 === '' &#63; '-' : value);
}
var url = location.origin + location.pathname + location.search + "#" + properties.join('|');
location.replace(url);
}
};
})(); 
Copy after login

This class has only 2 methods. The HashQuery.parseFromLocation() method deserializes the instance of the HashQuery subclass from location.hash, and the HashQuery.updateLocation() method serializes and updates the instance of the current HashQuery subclass to the window. location.

You can see that the HashQuery class does not have any attributes. That is because we only defined a base class, and the attributes of the class are all defined in the subclass. This is also realistic, because the query conditions only know what attributes are on the specific page.

Also, please pay attention to serialization and deserialization here. The serialization here only uses the JavaScript reflection mechanism to separate the values ​​​​of all string attributes (in order) of the instance with "|"; while serialization is to separate the string with "|" and then use reflection to update it to the instance. properties (in order).

How to use the HashQuery class

It’s very simple to use.

The first step is to define a subclass and add the required query conditions 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();
})(); 
Copy after login

The second step is to call the HashQuery.parseFromLocation() and HashQuery.updateLocation() methods on the query page. The code below 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();//在这里调用的哦,从location反序列化object
updateFormByHashQuery();
$("#btnSearch").click(function() {
updateHashQueryByForm();
hashQuery.updateLocation();//在这里调用的哦,将查询条件序列化之后更新到location.hash
$("#lblCount").html("加载中...");
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("共 " + $("#hfPagerTotalCount").val() + " 个任务");
$("#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);
};
})(); 
Copy after login

Summary

This is all the knowledge about using location.hash to save the page state in our project. I don’t know how everyone handles such needs in their WEB projects?

The above content is the technique of location.hash saving page status introduced by the editor. I hope it will be helpful to everyone!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template