我正在尝试使用AJAX实现Facebook的页面导航。我写了以下代码。
if ("onhashchange" in window) {
window.onhashchange = function () {
locationChanged(window.location.href);
}
}
else {
var storedURL = window.location.href;
window.setInterval(function () {
if (window.location.href != storedURL) {
storedURL = window.location.href;
locationChanged(storedURL);
}
}, 250);
}
function locationChanged(e) {
if (window.location.href.include('#!')) {
var paths = window.location.href.split("#!");
if (paths.length >= 2) {
var pos = paths.length - 1;
if (paths[pos].startsWith("/"))
paths[pos] = paths[pos].substr(1);
$('#holder').load(paths[pos]);
}
}
else {
if (window.location.href.endsWith('Index.html')
|| !window.location.href.endsWith('.html')) {
//this is first page
redirect("Login.html");
}
}
}
$(document).ready(function() {
if (window.location.href.endsWith('Index.html')
|| !window.location.href.endsWith('.html')) {
//this is first page
redirect("Login.html");
}
captureLinks();
});
function captureLinks() {
$('a').click(function(e) {
e.preventDefault();
redirect($(this).attr("href"));
});
}
function redirect(page) {
var path = page;
if (window.location.href.include('#!')) {
var paths = window.location.href.split("#!");
var pos = paths.length - 2;
if (!paths[pos].endsWith("/"))
paths[pos] += "/";
if (!page.startsWith("/"))
page = "/" + page;
path = paths[pos] + "#!" + page;
}
else {
if (path.endsWith(".html"))
path = window.location.href.trimEndTill("/");
else
path = window.location.href;
if (!path.endsWith("/"))
path += "/";
if (!page.startsWith("/"))
page = "/" + page;
path += "#!" + page;
}
window.location.href = path;
}
好处是代码正在运行,但它只有一个问题。有一个Index.html页面,它是应用程序的主要输入页面,当我写的时候说...
将其转换为......
http://localhost:8081/#!/Login.html
哪个是完美的。但当我指出它说...
http://localhost:8081/Index.html
它正在制作......
http://localhost:8081/Index.html/#!/Login.html
由于没有名为“Index.html /”的页面,因此创建了404错误。我修改了代码,以便它可以检测到Index.html并在将其指向Login.html之前将其删除。虽然代码现在给出了正确的结果,即使Index.html为......
http://localhost:8081/#!/Login.html
但问题是,它永远不会使用$ .load函数在正文中加载该页面(Login.html)。有什么不对的吗?我还想知道我的代码是否足够有效?