A Better Ajax Back Button Solution

If you've spent any time coding an Ajax application you know that the one of the problems with Ajax is that it breaks the back button. You have probably seen solutions that use an iframe and a hash (#) in the url to fix this issue. While this works there is a much simpler way that I've been using in my applications for the last year or so.

The key is the A tag (also known as the anchor tag) and the name parameter with a hash in the url. The trick is to either dynamically create the element or to just change the value of the name parameter to the matching value of the hash.

Below is an example of changing the name of the anchor tag.

//Anchor Rename Object this could also be a simple function if preferred.
var AnchorRename=new Object();
AnchorRename.CreateObject=function(anchorname, anchorid){
this.anchorid=anchorid; //This is the id of the anchor element
this.anchorname=anchorname;
this.RenameAnchor(anchorname, anchorholerid);
};
AnchorRename.CreateObject.prototype={
RenameAnchor:function(anchorname, anchorid){
document.getElementById(anchorid).name = anchorname;
}
};

In this example you would pass in the new value of the name (which must be the same value as after the hash in the url) and the id of the anchor element.

Below is an example of dynamically creating the tag and name values.

//Anchor Rename Object
var AnchorRename=new Object();
AnchorRename.CreateObject=function(anchorname, anchorholderid){
this.anchorholerid=anchorholderid; //This is the id of the element to hold the new anchor
this.anchorname=anchorname;
this.RenameAnchor(anchorname, anchorholderid);
};
AnchorRename.CreateObject.prototype={
RenameAnchor:function(anchorname, anchorholderid){
var AnchorCode=document.createElement("a");
AnchorCode.setAttribute("name", anchorname);
document.getElementById(anchorholderid).appendChild(AnchorCode);
}
};
In this example you would pass in the new value of the name (which again must be the same value as after the hash in the url) and the id of the anchor element.

Now the question that you may be asking is how does creating or renaming the anchor element help with fixing the back button. That is where when you call the object comes into play. You need to create or rename the object before a link is clicked. So, I would recommend using an onmouseover and an onfocus event to call the create or rename of the element so that before a link is clicked the required anchor element will be created.

I hope that this post has shown an easier solution to fix the back button problem that occurs when we create Ajax applications. Now go out there and try using it on your applications!

Nhận xét

Bài đăng phổ biến từ blog này

Ký tự viết tắt trong chat & email

dung lượng RAM lớn nhất mà HĐH cấu trúc 32-bit nhận được

Ubuntu LAMP Server