我是一个相对较新的网页设计师。我当前的问题是我有一个动态加载内容和修改历史记录的网页。当网页从一个页面切换到另一个页面时,我能够动态更改内容,但是当我离开网站并使用历史记录返回它时,我不断收到 404 找不到页面。有没有办法解决这个问题?
<script type="text/javascript">
$(document).ready(function(){
$(function() {
$('#bodywrap').load('/common/index.php');
$('ul#nav li a').click(function(e) {
$("#loading").show();
href = $(this).attr("href");
loadContent(href);
// HISTORY.PUSHSTATE
history.pushState('', '', href);
e.preventDefault();
});
$(window).bind('popstate', function(event) {
$("#loading").show();
console.log("pathname: "+location.pathname);
loadContent(location.pathname);
});
});
function loadContent(url){
// USES JQUERY TO LOAD THE CONTENT
$('#bodywrap').load('/common/'+url+'.php');
$("#loading").hide();
$('li').removeClass('active');
$('a[href="'+url+'"]').parent().addClass('active');
}
});
</script>
最佳答案
使用散列,这样底层网络服务器就不会尝试在那里找到实际的文档。请记住,Web 服务器路由器首先运行。此外,您需要检查加载时的哈希值,以便在从历史记录重新加载或直接访问时提取正确的内容。试试这个:
$(document).ready(function(){
$(function() {
$('#bodywrap').load('common/index.php');
// Handle page load
loadHref();
// handle link click
$('ul#nav li a').click(function(e) {
$("#loading").show();
href = $(this).attr("href").substr(1);
loadContent(href);
// HISTORY.PUSHSTATE
history.pushState('', '', $(this).attr("href"));
e.preventDefault();
});
// Handle popstate
$(window).bind('popstate', function(event) {
$("#loading").show();
loadHref();
});
});
function loadContent(url){
// USES JQUERY TO LOAD THE CONTENT
$('#bodywrap').load('common/'+url+'.php');
$("#loading").hide();
$('li').removeClass('active');
$('a[href="'+url+'"]').parent().addClass('active');
}
function loadHref() {
var href;
var loadHref = window.location.href;
if (loadHref.indexOf('#') > -1) {
href = loadHref.substr(loadHref.lastIndexOf('#') + 1);
loadContent(href);
}
}
});
请注意,您的链接需要是哈希值:
<a href="#about">About</a>
关于jquery - 我回来后的动态网页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28361244/