我在我的 localhost
上工作并使用最新的 jQuery 版本。
我在根目录 (/) 中有一个页面是 "index.php"
。在 index.php 中,我运行我的 javascript 代码,如 "load()"
。例如,还有一个名为"/video"
的目录,其中也有一个"index.php"
文件。
因此,我使用 pushState 方法将 "/video/index.php"
加载到主页中的 div (main-container)
中。因此,url 从 "localhost/"
更改为 "localhost/video"
但页面未重定向或重新加载。
最后,我的问题是,当我从主 "index.php"
加载时,整个代码工作正常,但是当我转到确切的 URL (例如:"localhost/video"
) 它只显示页面本身。我想看到的是显示加载的 "localhost/video/index.php"
的主页。
或者:从另一个 Angular 来看:我怎样才能使 "/video/index.php"
页面重定向到 "index.php"
并在那里加载自身?
这是我执行此操作的代码:
$("#nav-wrapper a").click(function(preventLinks){
href = $(this).attr("href");
$("#main-container").load(href);
history.pushState('', 'New URL: '+href, href);
preventLinks.preventDefault();
});
最佳答案
您应该在 video/index.php
文件的顶部添加一个 if 语句来检查请求是否为 XHR。如果不是,则重定向到主页。您还需要检查请求是否已在主页上重定向。您可以在客户端使用 URL 的哈希部分执行此操作。
视频/index.php:
<?php
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' ) {
//request is ajax, serve normal page
} else {
redirect('/#video/index.php');
}
?>
/index.php:
<script>
$(document).ready(function(){
if(window.location.hash){
var href = window.location.hash;
$('#main-container').load(href);
history.pushState('','New URL: '+href, href);
} else {
//do normal stuff
$("#nav-wrapper a").click(function(preventLinks){
href = $(this).attr("href");
$("#main-container").load(href);
history.pushState('', 'New URL: '+href, href);
preventLinks.preventDefault();
});
}
});
</script>
另一种策略是在#main-container 中为整个根页面提供视频内容。这样一来,您就不必检测 URL 的哈希部分,并且您的主页 HTML 和 javascript 可以保持不变。
关于javascript - 文档只能用 jQuery 加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20928094/