我已经编写了以下内容来在我的应用程序中执行AJAX请求:
$(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");
}
});
});
});
但是我也想更改地址栏中的网址以匹配刚刚加载的网址。我使用新的HTML5历史记录API @ http://html5demos.com/history查看了一些演示,但它没有任何意义。< / p>
有人可以展示一个如何在我的代码中使用新历史记录的示例吗?真的很感激。感谢。
由于
答案 0 :(得分:4)
更改URL(没有哈希)并保持在同一页面的唯一方法是使用HTML5。而且你最好使用插件而不是编写自己的插件。
在您的情况下,每当您调用Ajax页面时,您都需要“推送”一个新的History状态。
也许你可以看看这个插件History.js
:
https://github.com/browserstate/History.js/
它的用法非常简单,您可以在文档中看到。
(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);