Location.hash save page State skills _javascript Tips

Source: Internet
Author: User
Tags serialization hasownproperty

The hash property is a readable, writable string that is the anchor part of the URL (the part starting with the # number).

Grammar

Location.hash

In our project, there is a large number of Ajax query form + Results list page, since the query results are returned by Ajax, when the user clicks on a list of items into the details page, and then clicks the Browser fallback button to return to the AJAX query page, then everyone knows that the query page's form and results are back 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 first page of the list, the experience user is really going crazy.

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

(This article may be difficult for JavaScript beginners because it involves JS object-oriented knowledge, such as defining classes, inheritance, virtual methods, reflection, etc.)

Let's see what we need.

Our project is a micro-H5 task management system, to complete the page prototype as shown in the following figure:

The requirements should be clear: Click on the query form, return the query results with Ajax, and click on one of the tasks in the list to enter the task details page. Because the Administrator (Project manager) will often handle multiple tasks at a time, so will continue to the task Details page with the Query List page switch, then if the return key can not save the query page status, then each return query page to re-enter the query conditions, such experience is certainly unbearable.

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

Solving ideas

There are a lot of ideas for saving page state, but we think that using location.hash should be the best way.

Ideas are as follows:

1. User input query criteria and click OK, we will query conditions serialized into a string, and through "#" Add query criteria to the URL after a new URL, and then call Location.replace (the new URL) to modify the address of the browser address bar.

2. When the user presses the fallback button to fall back to the query page, it can be said that when the page is loaded, the Location.hash is deserialized into a query condition, then the query condition is updated to the query form and the query can be executed.

The idea is very simple, the key is the Location.replace method, this method is not only to modify the browser address bar URL, more importantly, will replace the current page in the Window.history record. If you do not use the Location.replace method, each fallback will fall back to the previous query condition. Of course, such a requirement might be useful for some projects.

Final Solution

If this article is only to share the above solution, that value is not big. The value of this article should be the simple but powerful JavaScript class we wrote.

If you see the solution above, 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.L
Ength) {This[p] = Properties[index]; if (this[p] = = '-') {this[p] = ';}} index++;  }, Updatelocation:function () {var properties = []; for (Var p) {if!this.hasownproperty (P) | | typeof This[p]
!= ' string ') {continue;} var value = This[p]; Properties.push (Value = = = ""?
'-': value);
The var url = location.origin + location.pathname + location.search + "#" + properties.join (' | ');
Location.replace (URL);
}
}; })(); 

This class has only 2 methods, the Hashquery.parsefromlocation () method is deserialized from Location.hash to an instance of the Hashquery subclass, Hashquery.updatelocation () method to serialize and update the instance of the current Hashquery subclass to Window.location.

You can see hashquery this class has no attributes, because we only define a base class, and the properties of the class are defined in subclasses. This is also true because the query criteria only know what attributes are available on a specific page.

Also, note the serialization and deserialization here. The serialization here is simply using the JavaScript reflection mechanism to use the value "|" of all the string attributes (in order) of the instance. Delimited, and serialization is a string with "|" After separating, the properties of the instance are updated with reflection (in order).

How to use the Hashquery class

When used, it's very simple.

The first step is to define a subclass that adds the query criteria you need 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 ();

The second step is to call the Hashquery.parsefromlocation () and Hashquery.updatelocation () methods on the query page. The following code is our complete query page:

(function () {var url = {list: "/app/task/list"}; var hashquery = null; var pager = null; $ (document). Ready (Function (
{hashquery = new tasksearchhashquery (); hashquery.parsefromlocation ();//Call Here Oh, deserialize object from location
Updateformbyhashquery (); $ ("#btnSearch"). Click (function () {updatehashquerybyform (); Hashquery.updatelocation ();
The query condition is serialized and updated to Location.hash $ ("#lblCount"). HTML ("Load ...");
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=" + hash
Query.status + "&keyword=" + Hashquery.keyword;
};
pager.onloaded = function () {$ ("#lblCount"). HTML ("Total" + $ ("#hfPagerTotalCount"). Val () + "task");
$ ("#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 the whole knowledge of using Location.hash to save page state in our project. Do not know how to deal with this kind of demand in the Web project?

The above content is small make up to everybody introduced Location.hash saves the page state the skill, hoped to have the help to everybody!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.