I have written the following to do AJAX requests in my app:
$(document).ready(function () {
$('ul#ui-ajax-tabs li:first').addClass('selected');
$('#ui-ajax-tabs li a').click(function (e) {
e.preventDefault();
$("#ui-ajax-tabs li").removeClass("selected");
$(this).parents('li').addClass("loading");
var url = $(this).attr("href");
var link = $(this);
console.log(url);
$.ajax({
url: url,
success: function (responseHtml) {
$('div#ui-tab-content').html($(responseHtml).find('div#ui-tab-content > div#ui-ajax-html'));
$(link).parents('li').addClass('selected');
$("#ui-ajax-tabs li").removeClass("loading");
},
开发者_开发问答 error: function () {
$('div#ui-tab-content').html('<div class="message error">Sorry that page doesn\'t exist</div>');
$(link).parents('li').addClass('selected');
$("#ui-ajax-tabs li").removeClass("loading");
}
});
});
});
However I also want to change the url in the address bar to match what I just loaded in. I have looked around at some demos using the new HTML5 History API @ http://html5demos.com/history but it's not making any sense.
Could someone show an example of how I could use the new history stuff in my code? Would be really appreciated. Thanks.
Thanks
The only way to change the URL (without hashes) and staying in the same page is by using HTML5. And you're better off using a plugin than writing your own.
In your case, you would need to 'push' a new History state whenever you call the Ajax page.
Maybe you can take a look at this plugin History.js
:
https://github.com/browserstate/History.js/
Its usage is very simple, as you can see in the Docs.
(function(window,undefined){
// Prepare
var History = window.History; // Note: We are using a capital H instead of a lower h
if ( !History.enabled ) {
// History.js is disabled for this browser.
// This is because we can optionally choose to support HTML4 browsers or not.
return false;
}
// Bind to StateChange Event
History.Adapter.bind(window,'statechange',function(){ // Note: We are using statechange instead of popstate
var State = History.getState(); // Note: We are using History.getState() instead of event.state
History.log(State.data, State.title, State.url);
});
// Change our States
History.pushState({state:1}, "State 1", "?state=1"); // logs {state:1}, "State 1", "?state=1"
History.pushState({state:2}, "State 2", "?state=2"); // logs {state:2}, "State 2", "?state=2"
History.replaceState({state:3}, "State 3", "?state=3"); // logs {state:3}, "State 3", "?state=3"
History.pushState(null, null, "?state=4"); // logs {}, '', "?state=4"
History.back(); // logs {state:3}, "State 3", "?state=3"
History.back(); // logs {state:1}, "State 1", "?state=1"
History.back(); // logs {}, "Home Page", "?"
History.go(2); // logs {state:3}, "State 3", "?state=3"
})(window);
精彩评论