现在这是我的情况:我正在制作一个 CMS。单击链接时,我希望页面使用 Ajax 动态加载。链接中的问题!
实时更改地址栏中地址的唯一方法是使用锚标记。但是 PHP 没有得到锚标签,因此我无法使用 PHP 在站点加载时加载页面内容。如果我要使用查询字符串加载页面,则单击链接时无法在地址栏中更新查询字符串,因为这会重新加载页面。
我想 Javascript 可以检查地址,将锚标记保存在 cookie 中并重新加载页面,但我宁愿不必花这么多时间。
有谁知道这个问题的解决方案?
现在这是我的情况:我正在制作一个 CMS。单击链接时,我希望页面使用 Ajax 动态加载。链接中的问题!
实时更改地址栏中地址的唯一方法是使用锚标记。但是 PHP 没有得到锚标签,因此我无法使用 PHP 在站点加载时加载页面内容。如果我要使用查询字符串加载页面,则单击链接时无法在地址栏中更新查询字符串,因为这会重新加载页面。
我想 Javascript 可以检查地址,将锚标记保存在 cookie 中并重新加载页面,但我宁愿不必花这么多时间。
有谁知道这个问题的解决方案?
不久前有一个类似的问题,我想出了以下解决方案。
您的 url 应该指向真实页面,以使其适用于 js 禁用用户。点击处理程序应该处理 ajax 请求。Hash 应该包含 url,以及一个&ajax
表示请求类型的部分。
如果请求来自 ajax,只需发送内容。如果不是,请将内容包装到页眉和页脚中,以使用完整的站点进行响应。
网址应该与链接到 ajax 生成的哈希并将它们用作链接一起使用。整个想法基本上是模仿你可以在 facebook 上看到的那种行为。
Javascript
// click handler for ajax links
function goToWithAjax(hash) {
hash = hash.href ? hash.getAttribute("href", 2) : hash;
ajax( hash, function( response ) {
document.getElementById("content").innerHTML = response;
});
hash = ("#!/" + hash).replace("//","/");
window.location.hash = hash;
return false;
}
.htaccess
auto_prepend_file = "prepend.php"
auto_append_file = "append.php"
前置
$url = $_SERVER['REQUEST_URI'];
$parts = explode('#!', $url);
$hash = isset($parts[1]) ? $parts[1] : false;
// redirect if there is a hash part
if ($hash) {
header("Location: $hash");
}
// find out if it's an ajax request
$ajax = strstr($url, "&ajax");
// we need header if it's not ajax
if (!$ajax) {
get_header();
}
附加
// we need footer if it's not ajax
if (!$ajax) {
get_footer();
}
get_header()
function get_header() {
echo <<< END
<html>
<head></head>
<body>
<div id="page">
<div id="header">
<div id="logo"></div>
<ul id="nav">menu...</ul>
</div>
<div id="content">
END;
}
get_footer()
function get_footer() {
echo <<< END
</div> <!-- end of #content --->
<div id="footer">(c) me</footer>
</div> <!-- end of #page --->
</body>
</html>
END;
}
我明白为什么您可能想使用 ajax 加载页面的某些部分。整个页面虽然毫无意义。
jQuery 解决方案可能类似于:
$(a.ajax_link).click(function(){
var url = $(this).attr('href');
$.ajax({
url:url,
success:function(data) {
$('body').html(data);
return false;
}
});
});
我从来没有测试过,但它应该在没有启用 javascript 的情况下仍然可以工作。