【发布时间】:2013-05-15 13:32:52
【问题描述】:
我尝试在我的网站上实现 pushstate 历史记录,以便从 index.php 容器内的单个.php 页面加载内容。
我的网站有两个主页:index.php 和 single.php。
在 index.php 上有调用 pushstate 脚本的链接:
<a class="phplink" href="/Formlabs-3D-printer" title="Formlabs 3D printer">Post 12</a>
<a class="phplink" href="/Minimal-Bumper-for-iPhone-5" title="Minimal Bumper for iPhone 5">Post 11</a>
在我的 single.php 页面上,我使用 isset get 方法动态加载与 index.php 上单击的链接对应的内容:
<?php
if (isset($_GET["page"])) {
//I do some stuff in order to echo content
?>
在我的 .htaccess 文件中,我重写了 url 链接(即 index.php 中的链接被清除的原因):
Options +FollowSymLinks
RewriteEngine on
RewriteRule /([a-zA-Z0-9\-]+)$ /index.php
RewriteRule /([a-zA-Z0-9\-]+)$ /single.php?page=$1 [L]
这里是我的 pushstate 脚本:
$.ajaxSetup({cache:false});
$(".phplink").click(function(){
var $post_link = $(this);
load_content($post_link.attr('title'),$post_link.attr('href'));
return false;
});
window.onpopstate = function(event) {
if (event.state) {
load_content(event.state.title, window.location.pathname, true);
} else {
var stateObj = {
title: document.title,
url: window.location.pathname,
};
url = window.location.pathname;
load_content(url,url);
}
}
function load_content(title,url,skipHistory) {
$.get(url,function (data) {
document.title = title;
var stateObj = {
title: title,
url: url
};
if (!skipHistory) {
if (typeof window.history.pushState == 'function') {
window.history.pushState(stateObj,title,url);
}
}
if(url.substring(1) != '') {
$("#ajaxify_container").html("loading...");
$("#ajaxify_container").load('single.php?page='+url.substring(1)+' #container-2');
}
else {
$("#ajaxify_container").html('');
}
});
}
我的 pushstate 脚本可以在链接点击(.phplink 点击)时加载内容。
它也适用于后退/前进按钮。
第一个问题:当我刷新浏览器(在 url 中带有 pushstate 链接)时,它可以在 google chrome 上运行(将内容从 single.php 加载到 index.php 容器),但在 IE10 中没有(没有加载任何内容,它保持打开状态) index.php 页面)。
第二个问题:如果我禁用 javascript 以查看 googlebot(对于 SEO)发生了什么。我无法加载/访问 single.php 页面,它总是停留在 index.php 上。所以single.php页面不能被搜索引擎抓取(我想,但我不确定)。 这种行为是正常的,因为我在我的 .htaccess 文件中设置了“所有这些链接”将被重定向到 index.php 。
我这样做是因为没有它 pushstate 在我刷新时会加载 single.php 页面。而且我不想要这种行为。我想在刷新时将内容从 single.php 加载到 index.php 容器中。
所以我的主要问题(问题 2)是:我不知道如何在我的 php 页面中编写脚本或链接,以便在单击时将内容加载到我的 index.php 文件中,我刷新并返回/前进。
在 pushstate 的正常行为中,是否在浏览器刷新时,onpopstate 可以将页面中的内容加载到另一个页面的容器中(将内容从 single.php 加载到 index.php 的容器中)?
我希望有人可以帮助我并解释它是如何工作的。我很难理解它是如何与链接一起工作的。
对不起我的英语,我是法国人......
【问题讨论】:
-
你删除了你原来的问题,所以我看不到你的回答是什么。为什么会有类似的重写规则?
-
我使用这个类似的重写规则,因为没有它,当我刷新浏览器时,它会进入 single.php 页面并加载它。使用此重写规则,当我刷新浏览器然后从 single.php 加载内容时,它会保留在 index.php 上。如果没有重写规则,我可以有这种行为吗?
-
我不熟悉 History API - 但我仍然认为您不应该有这样的路线。它应该始终指向一个文件...
-
是的,但是如果有人在他的浏览器中复制粘贴一个 url,它将重定向到单个页面上。我真的不明白用 pushstate 做这件事的方法是什么。不重写似乎是不可能的。我想念一些东西......
-
如果我只将这段代码留在 .htaccess 文件中:
RewriteRule /([a-zA-Z0-9\-]+)$ /index.php每个页面都会加载 index.php 。因此,如果我停用 javascript,我将无法加载 single.php 文件。 google bot 是否可以使用此规则看到这个动态的 single.php 文件?
标签: html seo hyperlink pushstate