通过js设置页面历史记录和页面内容
Set page history with page content by js
我使用了pace.js
,但pace
的问题是,加载动画是在页面完全加载后显示的。
因此,我尝试并制定了一个解决方案,点击页面上的每个链接,jquery从浏览器中获取并停止直接指向该链接的事件,并向该链接发送ajax get请求。加载页面时,会在当前页面上显示动画。页面完全加载后,它会用接收到的数据替换整个当前文档,并替换地址栏中的页面url。
<script type="text/javascript">
$( document ).ready(function() {
$('a').click(function() {
var dt;
if (/#/.test(this.href)) {
return true;
}else{
document.getElementById("before-loader").style.display= "block";//show loading animation
var that = this;
$.ajax({
type: "GET",
url: that.href,
success: function(response){
document.open();
document.write(response);
document.title = response.pageTitle;
window.history.pushState({"html":response.html,"pageTitle":response.pageTitle},"", that.href);
document.close();
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus + ' ' + errorThrown);
document.getElementById("before-loader").style.display= "none";//hide loading animation
}
});
return false;
}
});
});
</script>
问题是点击浏览器返回按钮,地址栏中的url正在更改,但页面内容仍然保持不变。我该如何克服这个问题?
更新
se0kjun
的答案并没有解决我的问题(我希望它能在复制/粘贴提供的代码后工作),但让我朝着正确的方向前进。经过一些研究和改写流程,它是有效的,但我仍然困惑它为什么有效。
$( document ).ready(function() {
$('a').click(function() {
if (/#/.test(this.href)) {
return true;
}else{
window.history.pushState(null, 'Production Workflow & Sales Management', this.href);
loadContent(this.href);
return false;
}
});
});
function loadContent(href) {
document.getElementById("before-loader").style.display= "block";
$.ajax({
type: "GET",
url: href,
success: function(response){
document.open();
document.title = response.pageTitle;
document.write(response);
document.close();
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus + ' ' + errorThrown);
document.getElementById("before-loader").style.display= "none";
}
});
}
window.onpopstate = function(event) {
link = location.pathname.replace(/^.*[''/]/, ""); // get filename only
loadContent(link);
};
也许我应该多学习。
我想您想要popstate
事件。
当您单击链接时,ajax请求that.href
。之后,如果请求成功,您将得到响应并调用pushstate
。
单击后退按钮时,会触发popstate
事件。您可以在popstate
事件处理程序中加载上一页。
以下是popstate
的使用示例
window.onpopstate = function(event) {
//you add a path in pushstate
$('.container').load(event.state.path);
alert('popstate');
};
这是一个小提琴
相关文章:
- window.location替换并传递URL历史记录条目中的变量
- Javascript历史记录转换为php行
- 浏览器何时记录历史记录
- 输入类型按钮返回历史记录并返回顶部
- HTML5历史记录-返回上一个完整页面按钮
- Angular JS-如何强制浏览器记录历史以便快速路由
- asp.net网站文件下载历史记录
- 使用Ajax的后退按钮历史记录,URL中没有散列
- 历史记录和通过JavaScript修改的HTML
- Javascript:历史记录未加载页面
- 通过js设置页面历史记录和页面内容
- 如果没有历史记录,我如何隐藏图像或按钮onclick=;历史.go(-1);
- 将HTML表单发布到iframe会导致浏览器历史记录出现问题
- 如何防止浏览器在历史记录中缓存HTML
- 如何将新的stateObject添加或附加到历史记录中
- 检查浏览器后退按钮历史记录
- React-router 在添加历史记录后不会渲染组件
- 如何返回可用的历史记录状态数
- 引导选项卡不适用于历史记录.返回选项
- 非用户发起的操作触发的导航没有记录历史