我正在尝试使用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
这是创造的404错误,因为没有名为“index.html页面/”。我修改了代码,以便它可以检测到Index.html并在将它指向Login.html之前将其删除。虽然代码,即使现在的index.html给出正确的结果......
http://localhost:8081/#!/Login.html
但问题是,它从来没有使用$ .load功能加载页面(login.html的)的身上。有什么不对的吗?我也想知道我的代码是否足够有效?
我正在利用$ .string jquery对象,所以请忽略一些函数,如include,startsWith,endsWith等。 – Neutralizer 2011-01-20 14:17:12