我正在嘗試使用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