As we all know one of the great benefits of implementing AJAX is the possibility of updating content without having to navigate to a new Web page. With this comes the drawback that the user can not come back to the last action, and doesn’t have a navigation link for his AJAX generated page.
The solution: using window.location.hash to keep information regarding AJAX action.
For example let’s say an AJAX request is done when a button is pressed in the page, and when that button is pressed the AJAX request load’s data for that buttons id, we will add required data to the window.location.hash, like this:
-
$ ( '#book1' ) .click ( function ( ) {
-
//add to hash data that you need to make the AJAX request later
-
$ (window ) .location .hash =$ (this ) .attr ( 'id' ) ;
-
$ .ajax ( {
-
type : "POST" ,
-
url :current_url ,
-
dataType : "html" ,
-
data : 'selection_id=' +$ (this ) .attr ( 'id' ) ,
-
success : function (html ) {
-
//do something
-
} } ) } )
Now on page load we need to grab the hash (if it exists and make the appropriate request), like this:
-
$ (document ) .ready ( function ( ) {
-
if ($ (window ) .location .hash .length ) )
-
{
-
//we will use $(window).location.hash.replace('#','') in the "data" section of the AJAX request
-
$ .ajax ( {
-
type : "POST" ,
-
url :current_url ,
-
dataType : "html" ,
-
data : 'selection_id=' +$ (window ) .location .hash .replace ( '#' , '' ) ,
-
success : function (html ) {
-
//do something
-
} } )
-
}
-
} ) ;
And now you can navigate to your AJAX request.
Also I suggest using a special character at the beginning of the hash (like ‘!’), because when location.hash is changed the browser tries to move (lower) the position of the document to any DOM element with the id defined in the hash, so if hash is #book1, the browser will move (lower) the page to the DOM element, so if you use ‘!’ and have #!book1 the !book1 id doesn’t exist and you can avoid any problems.
Another idea is to integrate ‘Back’ actions for navigation, so when a user presses the ‘Back’ button of the browser, you will show the requested AJAX content. There are a couple of jQuery plugins out there had handle the hashchange event, and that you can use.
本文介绍如何利用jQuery在不刷新页面的情况下更新内容,并通过维护窗口位置的哈希值来实现用户操作历史的记录。文章提供了一个示例,演示如何在按钮点击时通过AJAX请求加载特定内容,并在页面加载时恢复上一次的操作状态。

被折叠的 条评论
为什么被折叠?



