我有一个从数据库加载动态内容的函数,当单击某些链接时调用它:
jQuery
<script>
function loadContent(href){
$.getJSON("/route", {cid: href, format: 'json'}, function(results){
$("#content_area").html("");
$("#content_area").append(results.content);
reinitFunc1();
reinitFunc2();
reinitFunc3();
// history.pushState('', 'New URL: '+href, href);
});
};
</script>
我想启用pushState
和onpopstate
。
我可以通过取消注释以上行来启用 URL 和浏览器历史记录更改history.pushState
- 在多个页面之间向前和向后导航可以正常工作。
但这不会加载内容。
不久前,我认为通过添加这些元素,我拥有了完整的功能(即导航和内容加载):
window.onpopstate = function(event) {
console.log("pathname: "+location.pathname);
loadContent(location.pathname);
};
因此,我尝试将它们添加到单独的块中:
<script>
$(document).ready(function() {
window.onpopstate = function(event) {
console.log("pathname: "+location.pathname);
loadContent(location.pathname);
};
});
</script>
但这会导致导航时的页面范围被限制为一个,并且我无法向前导航。
如何以上述代码为基础实现导航和内容加载?
编辑
作为参考,正确的路径在浏览器历史记录中,只是它们无法导航(FF 和 Chrome)并且相应的内容没有加载。Firebug 中没有错误。