Using the back and forward buttons with the History API Using the back and forward buttons with the History API ajax ajax

Using the back and forward buttons with the History API


the data object is wrong, that is why you get that problem. An object is defined by key,values pair:

object = {key:'value'};$data = { text:$(responseHtml).find('#globalHtml'), type:'global', url:'the_url'};

not

$data = { $(responseHtml).find('#globalHtml'), 'global'};

Using the object definition you will get your data back using History.getState()

History.Adapter.bind(window,'statechange',function(){    var data = History.getState().data;    if(data){        var html = data.text;        var type = data.type;        var type = data.url;        if(html && type){            if(type == 'global'){                // just change html                $('.mainContent').html(html);                // call the App object's function                if(url) App.localLoad(url);            }else{                $('.localContent').html(html);            }        }    }})

NOTE:

  • when statechange event get's fired if any data is present it will fire the ajax calls
  • to simulate the ajax call without making it just change the title also, I think that will cover it

EDIT

  • the data object is actually taken from History.getState().data not History.getState()
  • added another param to the stored object to preserve url
  • using the url and the type you can make a call to the same function as in the onClick event

PROBLEM:

Uncaught TypeError: Converting circular structure to JSON

An object is referencing itself somewhere; hence the message "circular structure.". That means you are trying to stringify a object that has a reference to itself, this usualy happens with DOM elements. You should really consider changing

$data = { $(responseHtml).find('#localHtml'), 'local'};

to:

$data = { html:$(responseHtml).find('#localHtml').html(), type:'local'};

Notice the keys for the object (html and type) and the html function call (.html()), this way you wont send unnecessary data, just the html. If you need to use the html data when loading it as a DOM object just use this:

var DOM_Element_loaded = $('<div>').html(html_loaded);

now you can use DOM_Element_loaded to search/manipulate data in the html loaded without needing to attach it to the body.


NOTE: this is really more of a comment than an answer, but you get better syntax highlighting with answer responses.

This is what I did when I ran into this problem. If I remember correctly, this prevented the double-request problem.

window.onpopstate = function(event) {  if (event.state && event.state.initialHref) {    // make an AJAX request    // URL for AJAX request is event.state.initialHref  }}

When I use history.pushState() / history.replaceState(), I am defining an initialHref property in the object for the 1st argument. I am using an absolute URL for this value, not a relative one.