我在php中开发web应用程序,并使用ajax请求从服务器获取页面例如,点击菜单选项卡ajax请求页面从服务器并加载到特定的HTMldiv的index.php。所以所有的页面都在index.php指定的htmldiv
因此,在点击浏览器后退按钮时,它始终保持在默认页面上。如何启用浏览器后退/前进按钮功能,使其保持以前的页面状态
正如评论中提到的,HTML5历史API提供了你正在寻找的功能,但是如果你必须支持浏览器而不保证这些浏览器会支持历史API,那么看看jQuery BBQ插件,它会让你找到你需要的地方。重要的一点是要记住,您将使用URL标签来记录"页面加载",这只是真正的ajax加载。
像这样的东西应该可以做到这一点,但我还没有测试过:
(function($, window) {
function supports_history_api() {
return !!(window.history && history.pushState);
}
if (!supports_history_api()) { return; } // Doesn't support so return
function swapContent(href) {
$.ajax({
url: href,
cache: false
}).done(function( data ) {
var parser = $("#parser"); //Some empty and hidden element for parsing
parser.html(data);
var parsed = parser.find(".container").contents(), //Get the loaded stuff
realContainer = $(".container").first(); //This one wasn't loaded
realContainer.html(parsed);
parser.contents().remove(); //Empty the div again
});
}
$(".aTag").on("click", function(e) { //Select the links to do work on
var href = $(this).attr("href");
swapContent(href);
e.preventDefault();
history.pushState(null, null, href); //Push state to history, check out HTML 5 History API
});
window.onpopstate = function() {
swapContent(location.href);
};
})(jQuery, window);
一些HTML:
<div class="container">
<a class="aTag" href="tiles_1.html"><img src="img/tiles_1.jpg" /></a>
<a class="aTag" href="tiles_2.html"><img src="img/tiles_2.jpg" /></a>
<a class="aTag" href="tiles_3.html"><img src="img/tiles_3.jpg" /></a>
<a class="aTag" href="tiles_4.html"><img src="img/tiles_4.jpg" /></a>
</div>
//Loaded content gets pushed here for parsing
<div id="parser" style="display:none;"></div>