我正在使用jQuery在一个div容器中动态加载内容。
服务器端代码检测到请求是AJAX还是GET。
我希望浏览器的后退/前进按钮能够与代码一起工作,因此尝试使用history.pushState。我有以下代码片段:
$('.ajax').on('click', function(e) {
e.preventDefault();
$this = $(this);
$('#ajaxContent').fadeOut(function() {
$('.pageLoad').show();
$('#ajaxContent').html('');
$('#ajaxContent').load($this.attr('href'), function() {
window.history.pushState(null,"", $this.attr('href'));
$('.pageLoad').hide();
$('#ajaxContent').fadeIn();
});
});
});
除了在浏览器使用前进/后退按钮时,地址栏按计划更改但页面不更改之外,一切工作正常。我做错了什么?
在查看了克莱顿的答案后更新了脚本
var fnLoadPage = function(url) {
$('#ajaxContent').fadeOut(function() {
$('.pageLoad').show();
$('#ajaxContent').html('').load(url, function() {
$('.pageLoad').hide();
$('#ajaxContent').fadeIn();
});
});
};
window.onpopstate = function(e) {
fnLoadPage.call(undefined, document.location.href);
};
$(document).on('click', '.ajax', function(e) {
$this = $(this);
e.preventDefault();
window.history.pushState({state: new Date().getTime()}, '', $this.attr('href'));
fnLoadPage.call(undefined, $this.attr('href'));
});