4

I have an application which works heavily on AJAX. However I want to have navigation functionalities in it. To spoof the url, I am changing the location.hash, to generate URL. But if I use back/fwd, only the url changes, but page wont reload. How can I override the hstory.back to reload the page.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Rakesh
  • 5,793
  • 8
  • 36
  • 37
  • 1
    You might want to rename the title of the question to be a bit more specific. How about "Reloading a page with ajax when user clicks the browser back button" or something similar? – Antti Tarvainen Mar 10 '09 at 11:39

4 Answers4

7

I don't know of any other way than continuous polling to implement this behaviour. An implementation might look like this:

var lastHash = '';

function pollHash() {
    if(lastHash !== location.hash) {
        lastHash = location.hash;
        // hash has changed, so do stuff:
        alert(lastHash);
    }
}

setInterval(pollHash, 100);
Christoph
  • 164,997
  • 36
  • 182
  • 240
  • Thanks, it's very useful. A small improvement can be added to it, if you wrap the whole expression in a function statement which you invoke immediately, and the return value of that function would be the function you wrote. This way you can eliminate a global binding. – viam0Zah May 22 '09 at 10:19
  • I think this is what Török was talking about. Seems to work fine. Feels a little cleaner because of the encapsulation. var hashChecker = function(){ lastHash = location.hash; return setInterval(function() { if(lastHash !== location.hash) { lastHash = location.hash; } }, 50); }() – Derek Gathright Feb 06 '10 at 10:21
3

You can't exactly capture the back event, but most of these problems have been solved - and a good thing too, it's a hard problem.

Take a look at really simple history (aka RSH) and either implement it or work through it to see how it works.

annakata
  • 74,572
  • 17
  • 113
  • 180
1

The answer for this question will be more or less the same as my answers for these questions:

In summary, two projects that you'll probably want to look at which explain the whole hashchange process and using it with ajax are:

  • jQuery History (using hashes to manage your pages state and bind to changes to update your page).

  • jQuery Ajaxy (ajax extension for jQuery History, to allow for complete ajax websites while being completely unobtrusive and gracefully degradable).

Community
  • 1
  • 1
balupton
  • 47,113
  • 32
  • 131
  • 182
0

The balupton answers are really great.

But you also have another jQuery Plugin to handle your ajax requests, it is address.

Thiago Diniz
  • 3,041
  • 5
  • 30
  • 35