Home Web Front-end JS Tutorial Location.hash techniques for saving page status_javascript techniques

Location.hash techniques for saving page status_javascript techniques

May 16, 2016 pm 03:03 PM
location.hash

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

How do I use source maps to debug minified JavaScript code? How do I use source maps to debug minified JavaScript code? Mar 18, 2025 pm 03:17 PM

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

See all articles