Javascript 加载AJAX后创建可共享链接
在我的页面上,内容容器根据单击的列表项(新闻、视频、博客等)保存不同的信息 这是通过使用jQuery的load方法加载html片段实现的,如下所示:Javascript 加载AJAX后创建可共享链接,javascript,php,jquery,html,ajax,Javascript,Php,Jquery,Html,Ajax,在我的页面上,内容容器根据单击的列表项(新闻、视频、博客等)保存不同的信息 这是通过使用jQuery的load方法加载html片段实现的,如下所示: $('#container').load('blog.html'); // file from my domain 加载后,我可以使用以下方法更新URL: window.history.pushState("www.mysite.com", "mysite", "/blog"); 或更改哈希: window.location.hash = "
$('#container').load('blog.html'); // file from my domain
加载后,我可以使用以下方法更新URL:
window.history.pushState("www.mysite.com", "mysite", "/blog");
或更改哈希:
window.location.hash = "blog";
当直接访问链接时,这会导致错误,因为我的主机上不知道此类页面。在AJAX加载之后,我想知道最好的方法是如何使页面的当前状态可共享(我将链接发送给某人,当他们访问它时,他们看到页面的状态与我共享链接时的状态相同)?该链接类似于:www.mysite.com/blog
AJAX
加载:
$('li a').on('click', function(){
var file = this.id;
$('#container').load(file +'.html');
// window.history.pushState("www.mysite.com", "mysite", "/" + file); or..
// window.location.hash = file;
return false;
});
p.S.为了简单起见,我想避免使用
php
,但我愿意接受所有建议。在页面加载时,检查window.hash。如果它不是空的,那么做与使用时相同的事情好吧,如果使用哈希,正如您在OP中已经声明的那样,直接访问它时应该没有错误。(例如:www.mysite.com/#blog
)
加载时javascript可以检查是否设置了哈希,并再次执行必要的ajax调用以从直接链接提供页面。(顺便说一下,PHP无法看到散列,因此仅使用散列无法从PHP服务器端控制。)
使用pushState(例如:www.mysite.com/blog
)是另一回事。。。这需要您创建一个.htaccess,它将重写(例如)index.php。php可以使用javascript逻辑查看请求的url,以使用Ajax再次加载所需的内容。(如果使用PHP,甚至不使用ajax)
javascript(配置.htaccess以重写包含此javascript的文件后):
或者在php中(配置.htaccess以重写包含此php的文件后):
使用window.history.pushState时会发生什么情况?
$.ready( function() {
if (window.location.hash == "blog") $(#container).load("blog.html");
});
$.ready( function() {
if (window.location.pathname == "/blog") $(#container).load("blog.html");
});
<div id="container">
<?php
if ($_SERVER["REQUEST_URI"] == "/blog") {
include("blog.html");
}
?>
</div>