Javascript pushState和back按钮起作用,但内容不起作用';不变
它确实加载了一个新页面,url也更新了,但是当我按下后退按钮时,只有url没有刷新,但是内容没有Javascript pushState和back按钮起作用,但内容不起作用';不变,javascript,jquery,html,Javascript,Jquery,Html,它确实加载了一个新页面,url也更新了,但是当我按下后退按钮时,只有url没有刷新,但是内容没有 $('button').click(function(){ window.history.pushState({}, '', 'page2.php'); $('body').html('<div class="loading.gif"></div>'); //Load Page $.get('page2.php', function(data){ $
$('button').click(function(){
window.history.pushState({}, '', 'page2.php');
$('body').html('<div class="loading.gif"></div>');
//Load Page
$.get('page2.php', function(data){
$('body').html(data);
};
//Edited
$(window).bind('popstate', function(){
//What should I code here??
});
});
$(“按钮”)。单击(函数(){
pushState({},,'page2.php');
$('body').html(“”);
//加载页
$.get('page2.php',函数(数据){
$('body').html(数据);
};
//编辑
$(窗口).bind('popstate',function(){
//我应该在这里编码什么??
});
});
您需要实现popstate事件。按下状态后单击后退按钮,页面将接收popstate事件。在该事件中,您需要用正确的页面替换页面内容
看
更新代码:
$('button').click(function(){
// Store some information in the state being pushed
window.history.pushState({url:'page2.php'}, '', 'page2.php');
$('body').html('<div class="loading.gif"></div>');
//Load Page
$.get('page2.php', function(data){
$('body').html(data);
};
//Edited
$(window).bind('popstate', function(event){
var url = null;
if (event.state && event.state.url) {
url = event.state.url;
} else {
url = 'index.html'; // or whatever your initial url was
}
// Update the contents of the page with whatever url was stored in the state.
$.get(url, function(data){
$('body').html(data);
};
});
});
$(“按钮”)。单击(函数(){
//在正在推送的状态中存储一些信息
pushState({url:'page2.php'},,'page2.php');
$('body').html(“”);
//加载页
$.get('page2.php',函数(数据){
$('body').html(数据);
};
//编辑
$(窗口).bind('popstate',函数(事件){
var url=null;
if(event.state&&event.state.url){
url=event.state.url;
}否则{
url='index.html';//或任何初始url
}
//使用状态中存储的任何url更新页面内容。
$.get(url、函数(数据){
$('body').html(数据);
};
});
});
我做了类似的事情:
$(window).bind('popstate', function(){
window.location.href = window.location.href;
});
它工作得很好。代码从url中获取位置并重定向到此url。我使用此选项更改条形图地址并保存当前状态,包括当前html正文,并在单击back bouton时重新加载,无需任何其他ajax调用。所有内容都保存在浏览器中:
$.get(…)调用缺少一个右括号,但这可能只是您的示例中的一个问题。正在加载的图像是否显示?是的,图像确实显示。我的问题是“后退”按钮无法检索以前的内容。我对JS非常熟悉,您能告诉我在这种情况下如何实现popstate事件吗?谢谢!我已经编辑了我的发布,但我不确定在编辑的部分中添加什么来获取以前的内容?如果正确单击多个页面,这将不起作用?因为初始url也必须更新?只要您使用足够的信息来推送状态以生成以前的页面内容,它应该可以正常工作。保存的浏览器限制是什么状态中的对象?在firefox中:“因为firefox将状态对象保存到用户的磁盘,以便用户重新启动浏览器后可以恢复它们,所以我们对状态对象的序列化表示形式施加了640k个字符的大小限制。”这是整页重新加载。这不是历史API的目的。
$(document).ajaxComplete(function(ev, jqXHR, settings) {
var stateObj = { url: settings.url, innerhtml: document.body.innerHTML };
window.history.pushState(stateObj, settings.url, settings.url);
});
window.onpopstate = function (event) {
var currentState = history.state;
document.body.innerHTML = currentState.innerhtml;
};